[英]Base64 Encode a PDF in C#?
有人可以提供一些如何做到這一點? 我可以為常規文本或字節數組執行此操作,但不確定如何處理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的構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.