Results 1 to 3 of 3

Thread: Find the line number of a string

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jul 2009
    Posts
    140

    Find the line number of a string

    hi,
    i want to know the line number of a particular string in a text file.
    Code:
           string filePath = @"d:\file.txt";
                StreamReader streamReader = new StreamReader(filePath);
                string text = streamReader.ReadToEnd();
               
                streamReader.Close();
    
                string regMatch = "Active Routes:";//string to search for inside of text file. It is case sensitive.
                if (Regex.IsMatch(text, regMatch))//If the match is found in allRead
                {
                    Console.WriteLine("found\n");
                                
    
                }
    I want to have line number of the matching string
    If you found my reply helpful, please rate me

  2. #2
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Find the line number of a string

    My advice would be to read the file into a string array then cycle it with a for loop. Then you'll automatically be able to find the line number that the item is on.
    My Blog.

    Ryan Jones.

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Find the line number of a string

    First up, if you want to read all of a file then I'd suggest not using a StreamReader as there are easier ways. If you want to read the entire file as a single string then you should call File.ReadAllText and if you want to read the individual lines then you should call File.ReadAllLines.

    In your case you are looking for a line so you obviously want to read lines, but there's really no point reading the whole file if you don't have to. If you find a match on the first line then there's no point reading any further. As such, you should use a StreamReader and read the file line by line. You would start a counter at zero and increment it each time you call ReadLine. You then test the line you just read and, if it's a match, you use the current counter value and close the file.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width