Home > Software engineering >  get line number of string in file C#
get line number of string in file C#

Time:08-31

That code makes filter on the files with the regular expression, and to shape the results. But how can I get a line number of each matches in the file? I have no idea how to do it... Please help me

class QueryWithRegEx  
enter code here


   
    IEnumerable<System.IO.FileInfo> fileList = GetFiles(startFolder);  

   
    System.Text.RegularExpressions.Regex searchTerm =  
        new System.Text.RegularExpressions.Regex(@"Visual (Basic|C#|C\ \ |Studio)");  


    var queryMatchingFiles =  
        from file in fileList  
        where file.Extension == ".htm"  
        let fileText = System.IO.File.ReadAllText(file.FullName)  
        let matches = searchTerm.Matches(fileText)  
        where matches.Count > 0  
        select new  
        {  
            name = file.FullName,  
            matchedValues = from System.Text.RegularExpressions.Match match in matches  
                            select match.Value  
        };  


    Console.WriteLine("The term \"{0}\" was found in:", searchTerm.ToString());  

    foreach (var v in queryMatchingFiles)  
    {  
         
        string s = v.name.Substring(startFolder.Length - 1);  
        Console.WriteLine(s);  

      
        foreach (var v2 in v.matchedValues)  
        {  
            Console.WriteLine("  "   v2);  
        }  
    }  


    Console.WriteLine("Press any key to exit");  
    Console.ReadKey();  
}  

static IEnumerable<System.IO.FileInfo> GetFiles(string path)  
{  
    ...}

CodePudding user response:

You can Understand from this example:

Read lines number 3 from string

string line = File.ReadLines(FileName).Skip(14).Take(1).First();

Read text from a certain line number from string

string GetLine(string text, int lineNo) 
{ 
  string[] lines = text.Replace("\r","").Split('\n'); 
  return lines.Length >= lineNo ? lines[lineNo-1] : null; 
}

CodePudding user response:

Don't use File.ReadAllText but read one line after the other if you want the line number:

var queryMatchingFiles =
    from file in fileList
    where file.Extension == ".htm"
    from l in System.IO.File.ReadLines(file.FullName).Select((l, ix) => (Line: l, LineNumber: ix 1))
    let LineNumber = l.LineNumber
    let matches = searchTerm.Matches(l.Line)
    where matches.Any()
    select new
    {
        Name = file.FullName,
        LineNumber,
        LineMatches = matches.Select(m => m.Value)
    };

If you want all line matches together without reference to their file or line:

IEnumerable<string> allMatches = queryMatchingFiles.SelectMany(x => x.LineMatches);
  • Related