Skip to main content
 首页 » 编程设计

c#之OutOfMemoryException加载xml文档winmo 6.1

2024年02月24日21bhlsheji

我在 Windows Mobile 6.1 设备上使用 C#。紧凑的框架 3.5。 加载大量 XML 字符串时出现 OutofMemoryException。 手机内存有限,但应该足以处理 xml 字符串的大小。 xml 字符串包含一个 2 MB 文件的 base64 内容。当 xml 字符串包含最大 1.8 MB 的文件时,代码将起作用。
我完全不知道该怎么办。不确定如何更改任何内存设置。
我已经包含了下面代码的精简副本。感谢您的帮助。

 Stream newStream = myRequest.GetRequestStream(); 
                // Send the data. 
                newStream.Write(data, 0, data.Length); 
                //close the write stream  
                newStream.Close(); 
                // Get the response.  
                HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse(); 
                // Get the stream containing content returned by the server. 
                Stream dataStream = response.GetResponseStream(); 
                //Process the return 
                //Set the buffer 
                byte[] server_response_buffer = new byte[8192]; 
                int response_count = -1; 
 
                string tempString = null; 
 
                StringBuilder response_sb = new StringBuilder(); 
                //Loop through the stream until it is all written 
                do 
                { 
                    // Read content into a buffer 
                    response_count = dataStream.Read(server_response_buffer, 0, server_response_buffer.Length); 
                    // Translate from bytes to ASCII text 
                    tempString = Encoding.ASCII.GetString(server_response_buffer, 0, response_count); 
                    // Write content to a file from buffer 
                    response_sb.Append(tempString); 
                } 
                while (response_count != 0); 
                responseFromServer = response_sb.ToString(); 
                // Cleanup the streams and the response. 
                dataStream.Close(); 
                response.Close(); 
            } 
            catch { 
                MessageBox.Show("There was an error with the communication."); 
                comm_error = true; 
            } 
              if(comm_error == false){ 
            //Load the xml file into an XML object 
 
                  XmlDocument xdoc = new XmlDocument(); 
                  xdoc.LoadXml(responseFromServer); 
              } 

错误发生在 xdoc.LoadXML 行。我曾尝试将流写入文件,然后将文件直接加载到 xmldocument 中,但效果并不好。 在这一点上完全难住了。

请您参考如下方法:

我建议您使用 XmlTextReader 类而不是 XmlDocument 类。我不确定您对读取 xml 的要求是什么,但是 XmlDocument 非常占用内存,因为它创建了许多对象并尝试加载整个 xml 字符串。另一方面,XmlTextReader 类只是在您读取 xml 时扫描它。

假设你有字符串,这意味着你会做类似下面的事情

        String xml = "<someXml />"; 
        using(StringReader textReader = new StringReader(xml)) { 
            using(XmlTextReader xmlReader = new XmlTextReader(textReader)) { 
                xmlReader.MoveToContent(); 
                xmlReader.Read(); 
                // the reader is now pointed at the first element in the document... 
            } 
        }