Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
How can i find the line number of string in textfile in c#?
Posted

 
Share this answer
 
Comments
Ed Nutting 30-May-12 4:55am    
Good answer, my 5+ :)
Prasad_Kulkarni 30-May-12 4:59am    
A 1 vote with 5+ comment :D
Ed Nutting 30-May-12 5:01am    
Im very sorry im on my phone i bus realised i clicked the wrong star. Vote has been corrected :)
Prasad_Kulkarni 30-May-12 5:05am    
:) That's fine,
Thank You!
Counting newlines.




You might:
  1. Initialize lineno with 0.
  2. Read a line, increment lineno.
  3. If you find the string inside the line the exit (lineno contains the correct string line number) else go to point 2.

Note you should also handle the 'end-of-file before the string is found' condition.
 
Share this answer
 
Mohsen,

Have a look at my answer to exact/match question. That solution inform you the line number.
 
Share this answer
 
if you want that how many lines in the text file than you can use this code

C#
private int GetTotalLines(string FileNameWithPath)
{
    string[] bt = null;
    if (System.IO.File.Exists(FileNameWithPath))
    {
        bt = System.IO.File.ReadAllLines(FileNameWithPath);
    }
    return bt.Length;
}


if you want to find line no in which your search string is exist than you can use this function

C#
private int GetLinesNoFromFile(string FileNameWithPath,string searchString)
        {
            string[] bt = null;
            if (System.IO.File.Exists(FileNameWithPath))
            {
                bt = System.IO.File.ReadAllLines(FileNameWithPath);
            }

            for (int i = 0; i < bt.Length; i++)
            {
                string str = bt[i].ToString();
                if (str.Contains(searchString))
                    return i; // data found in line no
            }
            return -1; // nodata found
        }
 
Share this answer
 
v2
Comments
CPallini 30-May-12 4:56am    
What has it to do with the OP question?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900