|
-
Jan 6th, 2010, 01:15 AM
#1
Thread Starter
Addicted Member
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

-
Jan 6th, 2010, 06:43 AM
#2
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.
-
Jan 10th, 2010, 08:08 PM
#3
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|