In C#, File.OpenRead() opens an existing file for reading only and returns a FileStream. It is a short way to write File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read).
Use it when you want to read a file in pieces, such as a large binary file, instead of loading it all with ReadAllBytes. Other programs may still read the file while your stream is open, but they cannot write to it.
This is a static method of System.IO.File. Call it as File.OpenRead(...); there is no new File(). For an object that remembers one file, see FileInfo.
Syntax
Call it in a using statement and read bytes with Read or ReadByte.
Ask the stream.CanRead is True and CanWrite is False, because OpenRead asks the system for read access only.
Ten characters, ten bytes. Each digit is one byte in UTF-8, so Length prints 10.
Writing is refused.WriteByte throws NotSupportedException, so the file cannot be changed by mistake through this stream.
Example 3 — Read a File in Small Chunks
Use a loop and a small buffer, the pattern for files too big to load at once.
C#
using System;
using System.IO;
using System.Text;
class Program {
static void Main() {
string root = Path.Combine(Path.GetTempPath(), "codetofun-file-openread-chunks");
if (Directory.Exists(root)) Directory.Delete(root, true);
Directory.CreateDirectory(root);
string path = Path.Combine(root, "letters.txt");
File.WriteAllText(path, "ABCDEFGHIJ");
using (FileStream fs = File.OpenRead(path)) {
byte[] buffer = new byte[4];
int count;
while ((count = fs.Read(buffer, 0, buffer.Length)) > 0) {
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, count));
}
}
Directory.Delete(root, true);
}
}
Output
ABCD
EFGH
IJ
How It Works
A small buffer. The array holds four bytes, so each Read returns at most four. Real programs use sizes such as 4096 or more.
Loop until zero.Read returns 0 at the end of the file, which stops the while loop. This is the standard way to know you are done.
Decode only what arrived. The last pass returns two bytes, so GetString(buffer, 0, count) prints just IJ and ignores the old bytes still in the buffer.
Frequently Asked Questions
A read-only FileStream positioned at the start of an existing file. Writing to it throws NotSupportedException.
ReadAllBytes loads the whole file into one array and closes it. OpenRead gives you a stream so you can read in pieces, seek to a position, or stop early.
No. It throws FileNotFoundException. Use File.Open with FileMode.OpenOrCreate if you want the file created when it is missing.
Yes, as long as none of them opens it for writing in a way that blocks sharing. OpenRead allows other readers (FileShare.Read) but not writers.
Use OpenText (or StreamReader) for text, because it decodes the bytes for you. Use OpenRead for binary data or when you want to work with raw bytes.