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#

Jacob Saylor

Software developer in Kentucky

1 Response

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: