解密XML文件时出现“Out of Memory”异常

时间:2010-06-10 14:51:49

标签: c# xml encryption out-of-memory

我正在使用System.Security.Cryptography库来加密和解密xml文件。最近虽然我在尝试解密75MB文件时遇到了OOM(Out of Memory)异常。这是我正在使用的代码:

    using System.Security.Cryptography.Xml;
    ...
    public static XmlDocument DecryptIntoXmlDoc(string filename)
    {
        //Decrypt the XML
        XmlDocument xmldoc = new XmlDocument();
        EncryptedXml exml = new EncryptedXml(xmldoc);
        TripleDESCryptoServiceProvider ekey = new TripleDESCryptoServiceProvider();
        ASCIIEncoding encoding = new ASCIIEncoding();

        ekey.Key = encoding.GetBytes(GetMasterKey());
        exml.AddKeyNameMapping("ekey", ekey);
        xmldoc.Load(filename);

        // -- THROWS THE OOM ERROR --
        exml.DecryptDocument();

        //Clear exml
        exml = null;

        return xmldoc;
    }

一旦调用.DecryptDocument(),我就会收到以下错误:

 Exception of type 'System.OutOfMemoryException' was thrown.

我无法找到其他人遇到此问题,但我读过如果xml标签没有正确命名/嵌套,则加载到内存时文件可能非常大。 将我的XML标记重命名为较短的名称会减小大小吗?有没有办法嵌套xml标签来减小文件大小?

我还能做什么吗?

1 个答案:

答案 0 :(得分:0)

  • 在调试程序下运行程序
  • 抛出OOM异常时,请暂停并检查以exml为根的对象图。什么实际上占据了大部分内存?

不可变的字符串可能是这里的杀手,因为一些xml解析器最终可以将你的整个doc保存在内存中多次。

相关问题