December 7th, 2009How To User StreamReader to Open A File ReadOnly in C# (.NET)
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!









December 8th, 2009 at 5:03 am
Thanks Peter, I was just looking for something like this!
December 8th, 2009 at 1:06 pm
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?
December 8th, 2009 at 1:06 pm
Hi Ryan,
Sorry, don’t know about performance, but I’d guess opening in ReadOnly has not perf impact.
-Peter
July 23rd, 2010 at 11:27 am
File.OpenRead(file) .. doesn’t seem to work in VS 2010 C#. The only option (in Intellisense) I get is file.OpenFile no file.openRead. Any thoughts?
August 17th, 2011 at 12:47 pm
@Ash: I believe you are incorrect. I am using VS2010, and this works:
System.IO.StreamReader streamReader = new System.IO.StreamReader(System.IO.File.OpenRead(“myfile.txt”));
October 6th, 2011 at 2:46 pm
I beleive that you want to do something like this
using( FileStream s = File.OpenRead(filename))
{
using(TextReader reader = new StreamReader(s))
{
// Do smoething
}
}
This ensures the both streams get closed properly.
Cheers
Ben