[注意:此答案假設可以通過按順序將每塊寫入到某種形式的流處理以塊的最終底座64的字符串,例如]
如果寫這簡化一個輔助方法在最大尺寸的byte[]
塊讀取的文件,例如:
public static IEnumerable<byte[]> ReadFileInBlocks(string filename, int blockSize)
{
byte[] buffer = new byte[blockSize];
using (var file = File.OpenRead(filename))
{
while (true)
{
int n = file.Read(buffer, 0, buffer.Length);
if (n == buffer.Length)
{
yield return buffer;
}
else if (n > 0) // Must be the last block in the file (because n != buffer.Length)
{
Array.Resize(ref buffer, n);
yield return buffer; // Just this last block to return,
break; // and then we're done.
}
else // Exactly read to end of file in previous read, so we're already done.
{
break;
}
}
}
}
然後就可以編寫一個簡單的方法,以從依次文件返回基部的序列64串從字節的各塊變換:
public static IEnumerable<string> ToBase64Strings(string filename, int blockSize)
{
return ReadFileInBlocks(filename, blockSize).Select(Convert.ToBase64String);
}
然後假設你有處理每個轉換後的基本64串塊的方式,執行這樣的:
foreach (var base64String in ToBase64Strings(myFilename, 1024))
process(base64String);
或者,可以跳過中介ReadFileInBlocks()
方法和摺疊轉換到基座64串就像這樣:
public IEnumerable<string> ConvertToBase64StringInBlocks(string filename, int blockSize)
{
byte[] buffer = new byte[blockSize];
using (var file = File.OpenRead(filename))
{
while (true)
{
int n = file.Read(buffer, 0, buffer.Length);
if (n == 0) // Exactly read to end of file in previous read, so we're already done.
{
break;
}
else
{
yield return Convert.ToBase64String(buffer, 0, n);
}
}
}
}
100 MB應該不是問題。你的RAM是否滿了?你還需要base64字符串「在代碼中」還是你保存/發送到某個地方? – ChrFin
100MB可能很容易成爲一個問題,如果你一次又一次地做它 –
我有很多內存,但RAM編碼到base64時迅速增加。 base64字符串我用於保存和發送 – user3305198