Back

How to read file using StreamReader in C#?


Visit Stream I/O to know more about Stream class heirarchy.

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

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

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

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

//Close the StreamReader object after operation
sr.Close();
fs.Close();

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