Thursday, March 22, 2012

Convert a file to a byte array

///
/// Function to get byte array from a file
///

/// File name to get byte array
/// Byte Array
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;
}

No comments:

Post a Comment