Skip to content

How To User StreamReader to Open A File ReadOnly in C# (.NET)

Updated: at 02:12 PM

 

This is probably something pretty simple, hardly worth blogging about, but it took me a little while (15 minutes)  to figure out how to open a file ReadOnly with StreamReader,  so hopefully, next person looking will hit my blog post right away and save themselves 14 minutes.  StreamReader can be very useful in C#.

Say you have a block of code like the following for simply reading all lines of a file:

StreamReader streamReader = new StreamReader("myfile.txt")
string line;
  while ((line = streamReader.ReadLine()) != null)
  {  
       // do something      
   }

When you run this, you will quickly find out that the file gets opened read/write.

To open the file ReadOnly, you have to add a little bit of extra information to the StreamReader constructor call.

That is:

StreamReader streamReader = new StreamReader(File.OpenRead(file));

Hope this helps!

Check out the ORM (Object Relational Mapper) PRISMA. The database access method I use in all my projects