Following Base64Encode() method can be used Encode any file in to a Base64 string and write it in to a given file path. The Base64Decode() method can be used to generate original file from given Base64 String.
Basically Base64 can be used to encode a any file such as jpeg, avi, dat, txt, etc in to a String format.
private string Base64Encode()
{
string strBase64;
FileStream fileStream = new FileStream(msiFilePath, FileMode.Open, FileAccess.Read,
FileShare.Read);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
strBase64 = Convert.ToBase64String(buffer);
return strBase64;
}
private void Base64Decode(string filePath, string base64String)
{
FileStream fileStream = null;
try
{
byte[] plugInObjectBytes = Convert.FromBase64String(base64String);
fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
fileStream.Write(plugInObjectBytes, 0, plugInObjectBytes.Length);
fileStream.Flush();
}
catch (Exception ex)
{
if (File.Exists(filePath))
{
fileStream = null;
File.Delete(filePath);
}
throw;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
}
No comments:
Post a Comment