2013-01-16 42 views
2

我的代碼是如何解決C#中的System.OutOfMemoryException?

 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大文件的情況下被拋出和程序crashes.My操作系統是64位,並具有RAM 8GB的。

+1

該異常稱爲['OutOfMemoryException'](http://msdn.microsoft.com/en-us/library/system.outofmemoryexception.aspx),即使「MemoryOutOfException」會更好。 –

+0

哈哈哈。你在哪一行得到它? –

+0

在cs.FlushFinalBlock(); – mck

回答

1

試圖擺脫的所有緩衝區管理代碼,這可能是你的問題的原因...試着用兩個流工作(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(); 
    } 
}