小文件导致 OutofMemoryException

small file cause OutofMemoryException

我有一个加密文件,我先对其进行解密,然后尝试使用 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;
    }

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

现在可以了。谢谢大家的回答。