0

I am reading all lines in a text file using C# 7 as follows:

using (StreamReader reader = File.OpenText(file)) {    
  String line;    
  while ((line = reader.ReadLine()) != null) {

  }          
}   

For each line I also need to get the line number.

StreamReader does not seem to have a method for getting the line number.

What is the best way to do this?

David Arno
  • 42,717
  • 16
  • 86
  • 131
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

5 Answers5

4

I'd just create an integer to keep track of the line number myself.

using (StreamReader reader = File.OpenText(file)) {    
    var lineNumber = 0;
    String line;    
    while ((line = reader.ReadLine()) != null) {
        ...

        lineNumber++;
    }          
}  

Microsoft also uses such a variable to count the lines in one of the examples: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-read-a-text-file-one-line-at-a-time

Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • I believe the question is more about the line number being referred to here being the actual index of the line returned from the file and not a matter of incrementing the count of the lines being returned. – MicRoc Sep 08 '21 at 23:46
2

You should use your own local variable for it, like that:

using (StreamReader reader = File.OpenText(file)) {    
      String line;    
      int lineNum=0;
      while ((line = reader.ReadLine()) != null) {
         ++lineNum;
      }          
    }   
gyurix
  • 1,106
  • 9
  • 23
1

In addition to the other solutions here, I like to use File.ReadAllLines(string) to create a string[] result and then for (int i = 0; i < result.Length; i++)....

zambonee
  • 1,599
  • 11
  • 17
0

you can compute line number by your self:

using (StreamReader reader = File.OpenText(file)) {    
  String line;
  int n = 0;
  while ((line = reader.ReadLine()) != null) {
    n++;
  }          
}   
J. Anderson
  • 299
  • 1
  • 11
0

I know this is already solved and old but I want to share an alternative. The code just returns the line number where it founds a part of the string given, to have the exact one just replace "Contains" with "Equals".

public int GetLineNumber(string lineToFind) {        
    int lineNum = 0;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
    while ((line = file.ReadLine()) != null) {
        lineNum++;
        if (line.Contains(lineToFind)) {
            return lineNum;
        }
    }
    file.Close();
    return -1;
}
John M.
  • 76
  • 1
  • 4
  • 11