Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge
  • All
  • C#
  • MVC
  • Web API
  • Azure
  • IIS
  • JavaScript
  • Angular
  • Node.js
  • Java
  • Python
  • SQL Server
  • SEO
  • Entrepreneur
  • Productivity

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 ReadWrite
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.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.