Computers are good at following instructions, but not at reading your mind. --Donald Knuth
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

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

By steve on February 16, 2007.
Updated on January 22, 2012.
Viewed 23,623 times (1 times today).
Article TypesLanguage ElementsLanguagesTechnologies
SnippetIOC#.NET

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 = File.OpenRead(fullFilePath);
   try
   {
      byte[] bytes = new byte[fs.Length];
      fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
      fs.Close();
      return bytes;
   }
   finally
   {
      fs.Close();
   }

}

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

User Comments (3)

Posted 2011 Jun 27 23:28 PM. reply
For anyone reading this now, there is also File.ReadAllBytes(fullFilePath)

Qu4Z
Posted 2011 Jul 14 07:08 AM. reply
Note that fs.Close() is called twice on the same object. The first call to Close() could be removed. Also, could dispose of the FileStream in the finally block:

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

Zach D
Posted 2012 Jan 25 03:37 AM. reply
@Zach D: FileStream is IDisposable, so you could do away with try/finally and have:

using(FileStream fs = File.OpenRead(filePath))
{
  // ...
}

Kawahee
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.