0

I have a textfile which contains texts.Now i have a string say 945789 .Now i want to get the line on which this string is present from the textfile but i am not able to search and get the line.. Here is the code.

foreach (var line in File.ReadAllLines(pathToFile))
{
  //How to get the line with the string 
}

Please help me..

Update..

  for (int i = 9; i >=3; i--) {

  spsubcallingno = subcallingno.Substring(0, i);

   int lineNumber = 0;
   foreach (var spline in File.ReadAllLines(sp))
   {
   lineNumber++;
   if (line.Contains(spsubcallingno))
    {
   return lineNumber;
   }
   }
   }

I am getting a red line mark in return

user3699193
  • 27
  • 1
  • 8
  • Unless you keep an index you won't be able to know the line number if that's what you want. You can use a typical for loop and "i" is the line; right? – ChiefTwoPencils Jun 04 '14 at 09:42
  • 1
    http://stackoverflow.com/questions/6183809/using-streamreader-to-check-if-a-file-contains-a-string – Koryu Jun 04 '14 at 09:43

1 Answers1

2

Just use an int to count the lines:

public int GetLineNumber(string pathToFile, string content)
{
    int lineNumber = 0;
    foreach (var line in File.ReadAllLines(pathToFile))
    {
         lineNumber++;
         if(line.Contains(content))
         {
             return lineNumber;
         }
    }
    return lineNumber;
}

Where pathToFile is the path to the text file and content is the text to look for on the line e.g. 945789.

DGibbs
  • 14,316
  • 7
  • 44
  • 83
  • I have upadted my post ..Please see it ..I am getting error in return statetment – user3699193 Jun 04 '14 at 09:55
  • The return line assumes that this code is inside of a function that returns an int. If it's not, then you can change it to break; or use the updated answer provided. – DGibbs Jun 04 '14 at 10:32