如何在C#中将文件编码为base64以及如何检索它?
例如将zip文件编码为base64并再次检索它。
答案 0 :(得分:1)
最好的办法是使用ToBase64Transform和FromBase64Transform加密接口。
此代码示例背后的基本要点是,您将From / ToBase64Transform转换类与标准加密流一起使用,以处理将传入数据转换为base64或从base64转换数据的繁重工作。在ConvertToBase64
方法中,您会注意到它使用“ToBase64”加密流包装目标文件流,然后我们将内容从源流复制到base64加密流。在解码时也是如此,你只需稍微向后应用它。我们将源流包装在“FromBase64”中以对数据进行解码,我们使用它将其复制到目标流。
非常粗略(和未经测试的例子)类似于:
using System;
using System.IO;
using System.Security.Cryptography;
void ConvertToBase64(string sourceFileName, string destFileName) {
FileStream source = new FileStream(sourceFileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
FileStream dest = new FileStream(destFileName, FileMode.Create,
FileAccess.Write, FileShare.None);
ICryptoTransform base64 = new ToBase64Transform();
CryptoStream cryptoStream = new CryptoStream(dest, base64, CryptoMode.Write);
using (source) using (dest) using (base64) using (cryptoStream) {
source.CopyTo(cryptoStream);
cryptoStream.FlushFinalBlock();
}
}
void ConvertFromBase64(string sourceFileName, string destFileName) {
FileStream source = new FileStream(sourceFileName, FileMode.Open,
FileAccess.Read, FileShare.Read);
ICryptoTransform base64 = new FromBase64Transform();
CryptoStream cryptoStream = new CryptoStream(source, base64, CryptoMode.Read);
FileStream dest = new FileStream(destFileName, FileMode.Create,
FileAccess.Write, FileShare.None);
using (source) using (base64) using (cryptoStream) using (dest) {
cryptoStream.CopyTo(dest);
}
}