Reading line by line from a text file in C#

  • Thread starter Thread starter Eranga
  • Start date Start date
E

Eranga

I want to read line by line seperately from a .txt file. i.e. I want to
check each line for some specific word.
How can I do this.
Thanks in advance.
 
Use a StreamReader and then use the IndexOf (or regular expression) to
locate the specific location in each line.
 
Hi Eranga,

Use the ReadLine method of a StreamReader. You might also want to specify an Encoding other than UTF8 when creating the StreamReader object. Use the same encoding as the text file.

You can use String.IndexOf(searchword) to look for the word. For more complex searching, Regex might be your friend.
 
StreamReader sr = new StreamReader("filename.txt");
while (sr.Peek())
{
string test = sr.ReadLine();
//Do Something with test
}
 
Thank you all!
They were realy helpful.

How can I specify an Encoding other than UTF8 when creating the
StreamReader object??
 
Typically you would do something like this

using(StreamReader sr = new StreamReader(filepath, Encoding.ASCII))
{
// code here
}

This assumes the text file is ASCII encoded. Just replace Encoding.ASCII with the proper Encoding for your file. If you don't know the Encoding and the default UTF8 does not work, try Encoding.Default which is the same encoding your version of Windows uses.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top