gpt4 book ai didi

c# - OutOfMemoryException加载xml文档winmo 6.1

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:21 24 4
gpt4 key购买 nike

我在 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...
}
}

关于c# - OutOfMemoryException加载xml文档winmo 6.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3782217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com