File as a byte array in .NET

Wednesday, August 01, 2007 08:00 AM

So I had a situation where I found myself trying to load data from a file into a byte array so I can base64 encode the binary data to be passed along via something "web" based. I've never tried to do this before, because well almost everything I've ever encountered pertaining to data within files has been string based, so I typically parse on newlines. Below is my solution....

//Probably want to initialize the path variable prior to hitting this code block,
// and perform the proper exception handling.

using(FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
using (BinaryReader reader = new BinaryReader(stream))
{
    int number_of_bytes = (int) stream.Length;
    byte[] bytes = reader.ReadBytes(number_of_bytes);
    string encoded_data = Convert.ToBase64String(bytes);
    //Do something with the encoded_data.
}

Now of course the premise of my method above was to be able to load whatever is in the file into a byte array, my file had only a small amount of data in it (32 bytes to be exact), if you have a file on the order of kilobytes or greater I wouldn't advise this method, and would choose to process the data contained within the file in some kind of "chunked" fashion.