Tech Talk A software developer on all things tech, and then some

7May/121

Saving and Loading a Byte Array To File in C#

Need a quick way to save a byte array to file and read back? So did I, and thought I'd include this simple code snippet for anybody who needed it as well.

Includes

using system.IO;

Code : Saving to File

Note below, there are two additional options (besides the name) you can include in the FileStream, FileMode and FileAccess. FileMode lets you select the way you want to handle the file. Here we are going to select Create, to tell the program to either create the file or overwrite an existing one. Next, FileAccess lets you select the way the data is inserted. We are going to do a simple write since there won't be anything to append.

private void SaveByteArrayToFile(byte[] _ByteArray, string _FileName)
{
	try
	{
		//Open the stream for the file.
		using (FileStream _File = new FileStream(_FileName, FileMode.Create, FileAccess.Write))
		{
			//Write to file. The 0 included is for the offset (where to start reading from)
			_File.Write(_ByteArray, 0, _ByteArray.Count());
		}
	}
	catch (FileNotFoundException)
	{
		MessageBox.Show("Can not find the file " + _FileName);
	}
	catch (Exception ex)
	{
		//Do what you want here, I'm just going to display the error for simplicity
		MessageBox.Show(ex.Message);
	}
}

Code : Loading From File

Next let's load a byte array from file.

private byte[] LoadByteArrayFromFile(string _FileName)
{
	try
	{
		using (FileStream _File = new FileStream(_FileName, FileMode.Open, FileAccess.Read))
		{
			byte[] _ByteArray = new byte[_File.Length];
			int bytesRead = 0;
			int BytesToRead = (int)_File.Length;

			while (BytesToRead > 0)
			{
				int read = _File.Read(_ByteArray, bytesRead, BytesToRead);
				if (read == 0)
					break;
				BytesToRead -= read;
				bytesRead += read;
			}

			return _ByteArray;
		}
	}
	catch (FileNotFoundException)
	{
		MessageBox.Show("Can not find the file " + _FileName);
		return null;
	}
	catch (Exception ex)
	{
		MessageBox.Show(ex.Message);
		return null;
	}
}

Additional Resources

MSDN FileStream.Write

MSDN FileStream.Read

Related Posts

Create an Image or Bitmap Image from a Byte[], and a Byte[] from an image

Open Documents and Media in WPF's Web Browser Control in C#

5May/110

Create an Image or Bitmap Image from a Byte[], and a Byte[] from an image.

Have a filestream set up and need to produce an Image or Bitmap image from the blob? No worries, there are a few ways in doing this. First off, let me show you how to create the image or bitmap image from the byte array.

To an image specifically.

public Image byteArrayToImage(byte[] Inbyte)
{
    MemoryStream mStream = new MemoryStream(Inbyte);
    Image _image = Image.FromStream(mStream );
    return _image ;
}

To a bitmap specifically.

public BitmapImage byteArrayToBitmap(byte[] Inbyte)
{
    MemoryStream mStream = new MemoryStream(Inbyte);
    BitmapImage _bitmap = new BitmapImage();
    _bitmap .BeginInit();
    _bitmap .StreamSource = mStream ;
    _bitmap .EndInit();
    return _bitmap ;
}       

Both.

public void WriteImageToFile(byte[] Inbyte, String FileName)
{	
    FileStream aFile = new FileStream(FileName, FileMode.Create);

    //Write from the Inbyte byte array to the file
    aFile.Seek(0, SeekOrigin.Begin);
    aFile.Write(Inbyte, 0, Inbyte.Length);
    aFile.Close();
}

Now you are wondering how to get the image in the byte[] in the first place. Well that part is very simple. Here is a function that will read in the image and return the byte array for you

public void ImageTobyteArray(string Filepath)
{
    System.IO.File.ReadAllBytes(Filepath);
}
   
%d bloggers like this: