簡體   English   中英

如何在C#中解決System.OutOfMemoryException?

[英]How to solve System.OutOfMemoryException in C#?

我的代碼是

     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。

嘗試擺脫所有可能導致問題的緩沖區管理代碼...嘗試使用兩個流(對於易失性輸出而言,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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM