magritton
6/28/2014 - 8:39 PM

Takes a file from a path and turns it into an array

Takes a file from a path and turns it into an array

/// <summary>
/// Function to get byte array from a file
/// </summary>
/// <param name="_FileName">File name to get byte array</param>
/// <returns>Byte Array</returns>
public byte[] FileToByteArray(string _FileName)
{
    byte[] _Buffer = null;

    try
    {
        // Open file for reading
        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        
        // attach filestream to binary reader
        System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
        
        // get total byte length of the file
        long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
        
        // read entire file into buffer
        _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
        
        // close file reader
        _FileStream.Close();
        _FileStream.Dispose();
        _BinaryReader.Close();
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }

    return _Buffer;
}