How to read file in C# using streamreader?

 Posted on 09/05/2019

Share On: facebook gplus twitter
You can read your text file in C# using three classes which are FileInfo, FileStream and StreamReader. Each class have their own objects need to create with required parameter to locate file, open file and read file.

FileInfo - Create an object of FileInfo to locate your actual file path

FileStream - Open your file for Read by specifying parameters like Mode(This will create new file if it doesn't exists), Access(This will indicate read operation) and Share (Share file to other users to access it if its open already by any user)

StreamReader - Create an object of StreamReader by passing FileStream object on which it needs to assign and read your file content

Lets look into an example to read file.

//Assign specified file path
FileInfo fileInfo = new FileInfo(@"C:\SampleApplication\TestFile.txt");

//Specify different parameter with FileStream
FileStream fileStream = fileInfo.Open(FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);

//Assign StreamReader object to stream your file
StreamReader streamReader = new StreamReader(fileStream);

//ReadToEnd method is used to read all the content from your file
string fileContent = streamReader.ReadToEnd();

//Close objects after file read

Add Comment: