C# Code Snippet - Save byte array to file

C# Code Snippet - Save byte array to file

C# Code Snippet - Save byte array to file

(C-Sharp) C# code snippet save byte array in to an external file. This function useful to store binary data in files. This function can be use when retrieving binary data from database and save it to an external file.

Bookmark:

C# Code Snippet - Save byte array to file

This .Net C# code snippet save byte array in to an external file. This function useful to store binary data in files. Function return true if byte array successfully written to file, else return false. Most common method to store binary data in database is as a byte array format. This function can be use when retrieving binary data from database and save it to an external file. This function uses System.IO name space to open file using FileStream and reading from BinaryReader. Modify the exception handling section to as your project requirements.

/// <summary>
/// Function to save byte array to a file
/// </summary>
/// <param name="_FileName">File name to save byte array</param>
/// <param name="_ByteArray">Byte array to save to external file</param>
/// <returns>Return true if byte array save successfully, if not return false</returns>
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
    try
    {
        // Open file for reading
        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

        // Writes a block of bytes to this stream using data from a byte array.
        _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

        // close file stream
        _FileStream.Close();

        return true;
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }

    // error occured, return false
    return false;
}


Here is a simple example showing how to use above function (ByteArrayToFile). In this example we save byte array variable _ByteArray into a file byte-array.dat.

byte[] _ByteArray = ..... some data .....;

ByteArrayToFile("c:\\byte-array.dat", _ByteArray);


C# Keywords Used:

  • FileStream
  • FileAccess
  • FileMode
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, SQL, Byte array to file, FileMode, FileAccess
  • Programming Language : C# (C-Sharp)

External Resources:

Unixx :: June 04-2010 :: 06:28 PM

How would you do it with a float array? I get an error.My array,        public float[] post_x = new float[1000];

Leave a comment