Write A Byte[] To A Binary File

By Robbe Morris

Quick tip for writing a byte[] to a binary file. Often used to write byte[]'s from images in an app out to disk.

using System;
using System.IO;

public static void WriteBinaryFile(string fileName, byte[] binary)
{

    if (binary == null)  return;
    if (File.Exists(fileName)) File.Delete(fileName);

    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
       {
           bw.Write(binary);
        }
    }

}

//  In .NET 2.0, you can use the following

File.WriteAllBytes(fileName,byteArray);

Related FAQs

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.
Quick tip for converting an image loaded in your application to a byte[]. Often used to store images loaded into the app memory to a database.
Write A Byte[] To A Binary File  (524 Views)
Create New Account