Wednesday, August 13, 2008

Reads Binary file and encodes it to Base64 string using C#.NET

public static string BinaryToBase64String(string filePath)
{
try
{
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); // Creates new file stream for binary file with read access
BinaryReader binaryReader = new BinaryReader(fileStream); // Creates the binary reader with file as input
byte[] binaryByteArray = binaryReader.ReadBytes((int)fileStream.Length); // Reads the bytes from binay file and stores into byte array
return Convert.ToBase64String(binaryByteArray); // Encodes the byte array to Base64 string and returns the string
}
catch (Exception ex)
{
return ex.Message; // Returns the exception message
}
}