C# .NET Read Binary File Into Byte[]

By Robbe Morris

Learn how to read a binary file such as image file into a byte[] for storage in a database or perhaps utlitization in an IValueConverter for WPF or Silverlight.

using System;
using System.IO;

public static byte[] ConvertFileToByteArray(string fileName)
{
    
byte[] returnValue = null;

    
using(FileStream fr = new FileStream(fileName, FileMode.Open))
    {
        
using (BinaryReader br = new BinaryReader(fr))
         {
            
returnValue = br.ReadBytes((int)fr.Length);
         }
     }

    
return returnValue;

}

// In .NET 2.0 and above you can use if you do not require specific file open options.

  
var bytes = File.ReadAllBytes(fileName);

Related FAQs

Brief sample demonstrating how to read a text file in all at once.
A brief example demonstrating how to write a string to a file.
C# .NET Read Binary File Into Byte[]  (5710 Views)
Create New Account