Computers are good at following instructions, but not at reading your mind. --Donald Knuth

How Do I Read a File As an Array of Bytes in C#

By steve on Friday, February 16, 2007.
Updated Wednesday, August 28, 2013.
Viewed 134,791 times. (15 times today.)
DeveloperTips and Tutorials.NETC#

Summary

How do I read a file as an array of bytes?

.NET provides a lot of great tools for reading and writing files, lots of stream classes. If you're like me, I kind of find dealing with streams a pain. If I want to read a file I should only have to say "ReadFile" and the content should be there the way I want.

As a result, I tend to write lots of helper methods that hide the stream manipulations so I don't have to remember them. Here's one that will read any file as an array of bytes. I've found this useful with both binary and text files when I didn't have to analyze the data inside--such as a simple file transfer.

public static byte[] GetBytesFromFile(string fullFilePath)
{
   // this method is limited to 2^32 byte files (4.2 GB)

   FileStream fs = null;
   try
   {
      fs = File.OpenRead(fullFilePath);
      byte[] bytes = new byte[fs.Length];
      fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
      return bytes;
   }
   finally
   {
      if (fs != null)
      {
         fs.Close();
         fs.Dispose();
      }
   }

}

Update

The above is still a good way to read a file using a FileStream object, but a few years on and this functionality is now baked into the .NET framework.

byte[] bytes = File.ReadAllBytes("c:\folder\myfile.ext");
Back to Top

Share This Page:


Subscribe for free and read it when and where you want!

Get the latest tips and tools in your Inbox.

Your email address will NEVER be shared and you can unsubscribed at any time using the link at the bottom of every email.

Click Here to Subscribe

(Was this post helpful? If not, please leave a comment and let me know what you would like to hear about.)


 
comments powered by Disqus
Follow:
Share This Page:


Get the latest tips and tools in your Inbox. It's 100% free.



Click Here to Subscribe
Welcome!
Welcome to my blog about software development and the Microsoft stack.

I've been a full time .NET developer for fifteen years, but I didn't start my professional life as a programmer ... more