小文件导致OutofMemoryException

时间:2015-05-10 14:20:06

标签: c# out-of-memory deserialization

我有一个加密文件,我首先解密,然后尝试使用memorystreambinaryformatter对其进行反序列化,但是当我尝试将反序列化文件分配给列表时,我抓住了OutOfMemoryException(文件真的很小 - 17KB) 这是代码

byte[] encryptedData = File.ReadAllBytes(fileName); 
byte[] result = Decrypt(Algo, key, vector, encryptedData) ;
BinaryFormatter ser = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(result)) {
 try {
     files = ser.Deserialize(ms) as List<IItem>;
  } catch (OutOfMemoryException) {

  } catch (SerializationException) {
     MessageBox.Show("Incorrect password!");
     return;
  }
}

files = ser.Deserialize(ms) as List<IItem>; - 导致异常的原因 加密文件大小1696 解密1691后 - 正常大小。 这里解密代码

public byte[] Decode(byte[] data)
    {
        string key = ASCIIEncoding.ASCII.GetString(rc2.Key);
        string IV = ASCIIEncoding.ASCII.GetString(rc2.IV);
        ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key,rc2.IV);
        StringBuilder roundtrip = new StringBuilder();
        using (MemoryStream msDecrypt = new MemoryStream(data))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                int b = 0;

                do
                {
                    b = csDecrypt.ReadByte();

                    if (b != -1)
                    {
                        roundtrip.Append((char) b);
                    }
                } while (b != -1);
            }
        }
        byte[] decrypted = ASCIIEncoding.ASCII.GetBytes(roundtrip.ToString());
        return decrypted;
    }

1 个答案:

答案 0 :(得分:0)

@MineR和@HansPassant是正确的问题是在解密时使用字符))我已经改变了我的代码

       public byte[] Decode(byte[] data)
    {
        ICryptoTransform decryptor = rc2.CreateDecryptor(rc2.Key,rc2.IV);
        byte[] decrypted = new byte[data.Length];
        using (MemoryStream msDecrypt = new MemoryStream(data))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
               csDecrypt.Read(decrypted, 0, data.Length);
            }
        }
        return decrypted;
    }

现在它有效。谢谢所有答案。