C# 小文件导致OutofMemoryException

C# 小文件导致OutofMemoryException,c#,out-of-memory,deserialization,C#,Out Of Memory,Deserialization,我有一个加密的文件,我先解密,然后尝试使用memorystream和binaryformatter对其进行反序列化,但当我尝试将反序列化的文件分配给列表时,我捕获了OutOfMemoryException(文件非常小-17KB) 这是密码 byte[] encryptedData = File.ReadAllBytes(fileName); byte[] result = Decrypt(Algo, key, vector, encryptedData) ; BinaryFormatter s

我有一个加密的文件,我先解密,然后尝试使用
memorystream
binaryformatter
对其进行反序列化,但当我尝试将反序列化的文件分配给列表时,我捕获了
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;
  }
}

@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;
    }

现在它开始工作了。Thx all for answers.

当抛出
OutofMemoryException
时,应用程序的内存消耗是多少?还有,你所处的环境是什么?移动应用还是桌面?x86或x64?大约12-13MB。enviroment MVS,桌面应用程序,x86解密做什么?它可能需要17KB的文件并将其转换为17GB。。。看看结果的长度。问题可能是您解密的字节无效,并且能够进行适当的反序列化。这个文件是你自己写的吗?您能检查结果是否等于Serialize的原始输出吗?StringBuilder需要什么?为什么不能直接获取csDecrypt的字节?BinaryFormatter在序列化对象时会生成字节。无法将字节转换为字符,并非所有可能的字节值都是有效的Unicode码点。使用ASCII时尤其糟糕,它只能表示0到127之间的值。因此,您解密的数据不可避免地会被破坏,BinaryFormatter将抛出一个错误。您只需要处理字节,删除在代码的加密和解密部分转换为字符的代码。
       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;
    }