How To User StreamReader to Open A File ReadOnly in C# (.NET)
Monday 7 December 2009 @ 6:14 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!
Comments (3) - Posted in ASP.NET 3.5  




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

  1. Bartek Says:

    Thanks Peter, I was just looking for something like this!

  2. Ryan Says:

    Nice, I did not know of that static method.

    Do you know if it improves performance/memory if opening a file for reading purposes only vs. opening it in RW mode?

  3. Peter Says:

    Hi Ryan,
    Sorry, don’t know about performance, but I’d guess opening in ReadOnly has not perf impact.
    -Peter

Leave a Reply