Back To FAQ

How to Read File using StreamReader in C#?

Visit Stream I/O to know more Stream & its class heirarchy.

Use StreamReader class to read physical file in C#. The following example shows how to read file using StreamReader.

Example: Read File using StreamReader
//Create object of FileInfo for specified path            
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");
//Open file for Read\Write
FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Read , FileShare.Read); 

//Create object of StreamReader by passing FileStream object on which it needs to operates on
StreamReader sr = new StreamReader(fs);

//Use ReadToEnd method to read all the content from file
string fileContent = sr.ReadToEnd();

//Close StreamReader object after operation

Notice that fi.Open() has three parameters: The first param is FileMode for creating and opening a file if it does not exist; the second parameter, FileAccess, is to indicate a Read operation; and the third parameter is to share the file for reading with other users while the file is open.