This is what I did to read an array of bytes using FileStream and it worked well. I have expanded the namespaces for the sake of technical clarity. You should chose the FileShare and FileAccess parameters as per your scenario.
byte[] buffer = null;
using (System.IO.FileStream stm = new System.IO.FileStream("c:\\YourFile.txt",
System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None))
{
buffer = new byte[stm.Length];
stm.Read(buffer, 0, Convert.ToInt32(stm.Length));
}
How to read the contents of the file as a String and not an array of bytes?
string buffer = null;
using (System.IO.FileStream stm = new
System.IO.FileStream("c:\\YourFile.txt",System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.None))
{
using (System.IO.StreamReader rdr = new System.IO.StreamReader (stm))
{
buffer=rdr.ReadToEnd();
}
}
Why is StreamReader better than converting the byte[] to string using the desired encoding?
The StreamReader class is powerful because it will examine the header bytes and determine the encoding scheme for you. You do not have to use System.Text.Encoding.UTF8.GetString().
Why use FileStream and why not System.IO.File.ReadAllBytes/ReadAllText ?
I wanted precise control on the file locking mechanism. In my scenario, I had a process that was polling a folder for incoming files. I wanted to be sure that when I read the file, the slow running process on the other end had completed its job and the file was ready for my process to read and analyze.
What are the drawbacks of reading the entire file as a single array of bytes?
If you are going to read a very large file all at once then you are placing a higher demand on your RAM. Think of an application which renders movies. You have a 100MB movie file. You do not want to read the entire file at once. You would rather have it read in chunks of say 100KB at a time, render the scenes and then move on to the next chunk. This makes your application more scalable. Your movie application is now more scalable. You can handle very large movies wihout running into the risk of System.IO.OutOfMemoryException.