C#解码编码大文件
因为项目中有个需求把文件转成base64,一开始做的思路,是直接把文件读到内存中,然后在内存里转成base64 。 但是因为这个方法是公共方法,考虑到别人也可能用到,如果别人转的是几个G的大文件,那么直接加载到内存中,肯定是不行的,会出现内存溢出。通过网上查找资料,总结整理成下面的方法。
下面这个方法,我测试的时候,文件大小32G,转成base64,需要20分钟。
// A code block
/// <summary>
/// Encode file content base64
/// </summary>
/// <param name="filein">Input file path,The file is unencoded</param>
/// <param name="fileout">Encoded output file path</param>
public static void EncodeBase64File(string filein, string fileout)
{
try
{
using (FileStream fs = File.Open(fileout, FileMode.Create))
using (var cs = new CryptoStream(fs, new ToBase64Transform(), CryptoStreamMode.Write))
using (var fi = File.Open(filein, FileMode.Open))
{
fi.CopyTo(cs);
}
}
catch (Exception ex)
{
Utils.Log.Warn("EncodeBase64File failed with " + ex.ToString());
}
}
/// <summary>
/// Decode file content base64
/// </summary>
/// <param name="filein">Input file path,The file is unencoded</param>
/// <param name="fileout">Encoded output file path</param>
public static void DecodeBase64File(string filein, string fileout)
{
try
{
using (FileStream fs = File.Open(fileout, FileMode.Create))
using (var cs = new CryptoStream(fs, new FromBase64Transform() , CryptoStreamMode.Write))
using (var fi = File.Open(filein, FileMode.Open))
{
fi.CopyTo(cs);
}
}
catch (Exception ex)
{
Utils.Log.Warn("DecodeBase64File failed with " + ex.ToString());
}
}