C# .NET Read Binary File Into Byte[]

By Robbe Morris

Use C# to read a binary file such as an image file into a byte[] or byte array via the FileStream and BinaryReader classes. File.ReadAllBytes in the System.IO namespace is available in .NET 2.0 and above. You can use it if you do not require specific file open options.

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;

}


C# .NET Read Binary File Into Byte[]  (11624 Views)