有人可以提供一些如何做到这一点?我可以为常规文本或字节数组执行此操作,但不确定如何处理pdf.我先把pdf填入字节数组吗?
使用File.ReadAllBytes
加载PDF文件,然后编码字节数组作为正常使用Convert.ToBase64String(bytes)
.
有一种方法可以在块中执行此操作,这样您就不必一次刻录大量内存.
.Net包含一个可以进行分块的编码器,但它实际上是一个奇怪的地方.他们将它放在System.Security.Cryptography命名空间中.
我已经测试了下面的示例代码,并且使用上面的方法或Andrew的方法得到相同的输出.
以下是它的工作原理:启动一个名为CryptoStream的类.这是一种插入另一个流的适配器.您将一个名为CryptoTransform的类插入CryptoStream(后者又连接到您的文件/内存/网络流),并在数据从流中读取或写入数据时对数据执行数据转换.
通常,转换是加密/解密,但.net也包括ToBase64和FromBase64转换,所以我们不会加密,只是编码.
这是代码.我包含了一个(可能名字很差)安德鲁建议的实现,以便您可以比较输出.
class Base64Encoder
{
public void Encode(string inFileName, string outFileName)
{
System.Security.Cryptography.ICryptoTransform transform = new System.Security.Cryptography.ToBase64Transform();
using(System.IO.FileStream inFile = System.IO.File.OpenRead(inFileName),
outFile = System.IO.File.Create(outFileName))
using (System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(outFile, transform, System.Security.Cryptography.CryptoStreamMode.Write))
{
// I'm going to use a 4k buffer, tune this as needed
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inFile.Read(buffer, 0, buffer.Length)) > 0)
cryptStream.Write(buffer, 0, bytesRead);
cryptStream.FlushFinalBlock();
}
}
public void Decode(string inFileName, string outFileName)
{
System.Security.Cryptography.ICryptoTransform transform = new System.Security.Cryptography.FromBase64Transform();
using (System.IO.FileStream inFile = System.IO.File.OpenRead(inFileName),
outFile = System.IO.File.Create(outFileName))
using (System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(inFile, transform, System.Security.Cryptography.CryptoStreamMode.Read))
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = cryptStream.Read(buffer, 0, buffer.Length)) > 0)
outFile.Write(buffer, 0, bytesRead);
outFile.Flush();
}
}
// this version of Encode pulls everything into memory at once
// you can compare the output of my Encode method above to the output of this one
// the output should be identical, but the crytostream version
// will use way less memory on a large file than this version.
public void MemoryEncode(string inFileName, string outFileName)
{
byte[] bytes = System.IO.File.ReadAllBytes(inFileName);
System.IO.File.WriteAllText(outFileName, System.Convert.ToBase64String(bytes));
}
}
我也在玩我附加CryptoStream的地方.在Encode方法中,我将它附加到输出(写入)流,所以当我实例化CryptoStream时,我使用它的Write()方法.
当我阅读时,我将它附加到输入(读取)流,所以我在CryptoStream上使用read方法.我附加哪个流并不重要.我只需要将相应的Read或Write枚举成员传递给CryptoStream的构造函数.