search text file using c# and display the line number and the complete line that contains the search keyword
Asked Answered
B

4

17

I require help to search a text file (log file) using c# and display the line number and the complete line that contains the search keyword.

Bushbuck answered 13/3, 2010 at 8:9 Comment(0)
R
25

This is a slight modification from: http://msdn.microsoft.com/en-us/library/aa287535%28VS.71%29.aspx

int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
    if ( line.Contains("word") )
    {
        Console.WriteLine (counter.ToString() + ": " + line);
    }

   counter++;
}

file.Close();
Reuben answered 13/3, 2010 at 8:17 Comment(5)
Now can you guide me how can i export the same to excel. i.e. line and line numberBushbuck
Hm... you want the line number in one cell, and the actual line in another? If so, instead of separating by the colon there (on ": "), separate them by comma (",") and then have Excel read that as a CSV file (comma-separated value).Reuben
no i need to built the functionality in the app itself to be able to export to excel... (requirements are such) .. please helpBushbuck
That I don't know how to do. I'd search the web for c# export excel or I'd open a new question about that.Reuben
Can be simplified significantly in .NET 4 by using foreach (var line in File.ReadLines("c:\\test.txt")), removing the need for StreamReader and Close.Usanis
T
15

Bit late to the game on this one, but happened across this post and thought I'd add an alternative answer.

foreach (var match in File.ReadLines(@"c:\LogFile.txt")
                          .Select((text, index) => new { text, lineNumber = index+ 1 })
                          .Where(x => x.text.Contains("SEARCHWORD")))
{
    Console.WriteLine("{0}: {1}", match.lineNumber, match.text);
}

This uses:

  • File.ReadLines, which eliminates the need for a StreamReader, and it also plays nicely with LINQ's Where clause to return a filtered set of lines from a file.

  • The overload of Enumerable.Select that returns each element's index, which you can then add 1 to, to get the line number for the matching line.

Sample Input:

just a sample line
another sample line
first matching SEARCHWORD line
not a match
...here's aSEARCHWORDmatch
SEARCHWORD123
asdfasdfasdf

Output:

3: first matching SEARCHWORD line
5: ...here's aSEARCHWORDmatch
6: SEARCHWORD123
Trifocal answered 23/9, 2014 at 0:56 Comment(0)
M
1

To export do Excel you can use the CSV file format, like the Pessimist wrote. If you are uncertain about what to write, try entering some data in MS Excel and click on "Save As" option in the Menu and choose CSV as file type.

Take care when writing a CSV file format as in some languages the default for separating values is not the comma. In brazilian portuguese, for example, the default is comma as decimal separator, dot as thousands separator and semicolon for separating values. Mind the culture when writing that.

The other alternative is using horizontal tabs as separators. Experiment to write a string, press the TAB key and then another string and paste it into Microsoft Excel. It is the default separator in that program.

If you're using an ad-hoc solution to your specific problem, either alternatives can be used without much thinking. If you are programming something to be used by other persons (or in other environments), mind the culture specific differences.

Oh, I've just remembered now: you can write a Spreadsheet using XML, you can do that with only the .NET package. I've done that years ago with C# .NET 2.0

Macintosh answered 11/1, 2012 at 15:20 Comment(0)
U
0

I had a requirement where I needed to search through a list of directories looking for particular file types, containing a specific search terms but excluding other terms.

For example let's say you wanted to look through C:\DEV and only find .cs files that have terms "WriteLine" and "Readline" but not the term "hello".

I decided to write a small c# utility to do just this:

This is how you call it:

class Program
{

    //Syntax:
    //FileSearch <Directory> EXT <ext1> <ext2> LIKE <TERM1> <TERM2>  NOT <TERM3> <TERM4>
    //Example:
    //Search for all files recursively in C:\Dev with an extension of cs that contain either "WriteLine" or "Readline" but not "hello"
    //FileSearch C:\DEV EXT .cs LIKE "WriteLine" "ReadLine" NOT "hello" 
    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("FileSearch <Directory> EXT <EXT1> LIKE <TERM1> <TERM2>  NOT <TERM3> <TERM4>");
            return;
        }
        
        Search s = new Search(args);
        s.DoSearch();
    }

}

This is the implementation:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

class Hit
{
    public string File { get; set; }
    public int LineNo { get; set; }
    public int Pos { get; set; }
    public string Line { get; set; }
    public string SearchTerm { get; set; }

    public void Print()
    {
        Console.WriteLine(File);
        Console.Write("(" + LineNo + "," + Pos + ") ");
        Console.WriteLine(Line);
    }
}


class Search
{
    string rootDir;
    List<string> likeTerms;
    List<string> notTerms;
    List<string> extensions;
    List<Hit> hitList = new List<Hit>();

    //FileSearch <Directory> EXT .CS LIKE "TERM1" "TERM2"  NOT "TERM3" "TERM4" 
    public Search(string[] args)
    {
        this.rootDir = args[0];
        this.extensions = ParseTerms("EXT", "LIKE", args);
        this.likeTerms = ParseTerms("LIKE", "NOT", args);
        this.notTerms = ParseTerms("NOT", "", args);
        Print();
    }


    public void Print()
    {
        Console.WriteLine("Search Dir:" + rootDir);
        Console.WriteLine("Extensions:");
        foreach (string s in extensions)
            Console.WriteLine(s);

        Console.WriteLine("Like Terms:");
        foreach (string s in likeTerms)
            Console.WriteLine(s);

        Console.WriteLine("Not Terms:");
        foreach (string s in notTerms)
            Console.WriteLine(s);

    }

    private List<string> ParseTerms(string keyword, string stopword, string[] args)
    {
        List<string> list = new List<string>();
        bool collect = false;
        foreach (string arg in args)
        {
            string argu = arg.ToUpper();
            if (argu == stopword)
                break;

            if (argu == keyword)
            {
                collect = true;
                continue;
            }
            if(collect)
                list.Add(arg);
        }
        return list;
    }



    private void SearchDir(string dir)
    {
        foreach (string file in Directory.GetFiles(dir, "*.*"))
        {
            string extension = Path.GetExtension(file);

            if (extension != null && extensions.Contains(extension))
                SearchFile(file);
        }
        foreach (string subdir in Directory.GetDirectories(dir))
            SearchDir(subdir);
    }

    private void SearchFile(string file)
    {
      
        using (StreamReader sr = new StreamReader(file))
        {
            int lineNo = 0;
            while (!sr.EndOfStream)
            {
                int pos = 0;
                string term = "";
                string line = sr.ReadLine();
                lineNo++;

                //Look through each likeTerm
                foreach(string likeTerm in likeTerms)
                {
                    pos = line.IndexOf(likeTerm, StringComparison.OrdinalIgnoreCase);
                    if (pos >= 0)
                    {
                        term = likeTerm;
                        break;
                    }
                }

                
                //If found make sure not in the not term
                if (pos >= 0)
                {
                    bool notTermFound = false;

                    //Look through each not Term
                    foreach (string notTerm in notTerms)
                    {
                        if (line.IndexOf(notTerm, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            notTermFound = true;
                            break;
                        }
                    }

                    //If not term not found finally add to hitList
                    if (!notTermFound)
                    {
                        Hit hit = new Hit();
                        hit.File = file;
                        hit.LineNo = lineNo;
                        hit.Pos = pos;
                        hit.Line = line;
                        hit.SearchTerm = term;
                        hitList.Add(hit);
                    }
                }

            }
        }
    }


    public void DoSearch()
    {
        SearchDir(rootDir);
        foreach (Hit hit in hitList)
        {
            hit.Print();
        }
    }

}
Underproduction answered 31/8, 2021 at 13:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.