gpt4 book ai didi

c# - 如何解决 C# 中的 System.OutOfMemoryException?

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:45 24 4
gpt4 key购买 nike

我的代码是

     private byte[] Invoke(Stream inputFileStream, CryptoAction action)
{
var msData = new MemoryStream();
CryptoStream cs = null;

try
{
long inputFileLength = inputFileStream.Length;
var byteBuffer = new byte[4096];
long bytesProcessed = 0;
int bytesInCurrentBlock = 0;

var csRijndael = new RijndaelManaged();
switch (action)
{
case CryptoAction.Encrypt:
cs = new CryptoStream(msData, csRijndael.CreateEncryptor(this.Key, this.IV), CryptoStreamMode.Write);
break;

case CryptoAction.Decrypt:
cs = new CryptoStream(msData, csRijndael.CreateDecryptor(this.Key, this.IV), CryptoStreamMode.Write);
break;
}

while (bytesProcessed < inputFileLength)
{
bytesInCurrentBlock = inputFileStream.Read(byteBuffer, 0, 4096);
cs.Write(byteBuffer, 0, bytesInCurrentBlock);
bytesProcessed += bytesInCurrentBlock;
}
cs.FlushFinalBlock();

return msData.ToArray();
}
catch
{
return null;
}
}

如果加密大小为 60mb 的大文件,则会抛出 System.OutOfMemoryException 并且程序崩溃。我的操作系统是 64 位并且有 8Gb 的内存。

最佳答案

尝试摆脱所有缓冲区管理代码,这可能是您问题的原因...尝试使用两个流( volatile 输出的 MemoryStream 很好):

using (FileStream streamInput = new FileStream(fileInput, FileMode.Open, FileAccess.Read))
{
using (FileStream streamOutput = new FileStream(fileOutput, FileMode.OpenOrCreate, FileAccess.Write))
{
CryptoStream streamCrypto = null;
RijndaelManaged rijndael = new RijndaelManaged();
cspRijndael.BlockSize = 256;

switch (CryptoAction)
{
case CryptoAction.ActionEncrypt:
streamCrypto = new CryptoStream(streamOutput, rijndael.CreateEncryptor(this.Key, this.IV), CryptoStreamMode.Write);
break;

case CryptoAction.ActionDecrypt:
streamCrypto = new CryptoStream(streamOutput, rijndael.CreateDecryptor(this.Key, this.IV), CryptoStreamMode.Write);
break;
}

streamInput.CopyTo(streamCrypto);
streamCrypto.Close();
}
}

关于c# - 如何解决 C# 中的 System.OutOfMemoryException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14368068/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com