Loading ...

How to Read from a text file in c#

0 (0votes)

Before we start with how to read from a text file in C# one should know about File, FileStream and StreamReader classes and the methods and properties they have. Also about FileAccess and FileMode enumeration

To open a file we use open method of File class by specifying the path to the file. To read the contents of the file, we also use the FileMode.Open enumeration member and FileAccess.Read .

FileMode.Open :- It opens an existing file and if the file doesn't exist it throws an exception.
FileAccess.Read :- It specifies that file will be opened with read only access.

Ex of how to read text from a file.

FileStream fstream= File.Open(@"C:\samplefile.txt",FileMode.Open,FileAccess.Read);

The File.Open returns an object of FileStream. Basically file stream is nothing but just a stream so the contents can be viewed by calling the Read or ReadByte methods of FileStream class.

There is another way of reading the contents of a file i.e by using StreamReader class.

StreamReader srd=new StreamReader(fstream);

Important thing to note is that StreamReader class read a stream as a string and not as a series of bytes. So,all the methods return either string or arrays of strings.

Another way to open a file for reading is through File class.The "File" class has a OpenText method which can be directly used in creating a StreamReader. OpenText method opens an existing file and returns a StreamReader object.

StreamReader srd=File.OpenText(@"C:\samplefile.txt");

ReadToEnd :- It reads all the characters through to the end of the stream
Close :- Closes the reader

To read out entire file:

It can be done by using the ReadAllText method to read out the entire file.


By this way we read out the entire text, sometimes we want to search for a particular piece of text in the file. Instead of reading out the entire file. It would be a good idea to search for a particular piece of text.

StreamReader srd=File.OpenText(@"C:\samplefile.txt");

 { string str=srd.ReadLine();
     //The moment we find the hello,we stop the readiing of the file and inform the user about it.
       Console.WriteLine(Found hello at:");


When looking through the large files, this is the best way of scanning files.


Comments (no comments yet)

  • :*
  • :*
  • :

Top Posts