【发布时间】:2019-06-05 04:55:12
【问题描述】:
我必须读取从 API 返回的 XML 元素中的文件内容 Base64 字符串。
我的问题是这个字符串可能很长,具体取决于文件大小。
起初,我使用XmlDocument 来读取XML。现在我使用XmlReader 来避免
System.OutOfMemoryException 当 XML 太大时。
但是当我阅读字符串时,我也收到了System.OutOfMemoryException。
我猜这个字符串太长了。
using (XmlReader reader = Response.ResponseXmlXmlReader)
{
bool found = false;
//Read result
while (reader.Read() && !found)
{
if(reader.NodeType == XmlNodeType.Element && reader.Name == "content")
{
//Read file content
string file_content = reader.ReadElementContentAsString();
//Write file
File.WriteAllBytes(savepath + file.name, Convert.FromBase64String(file_content));
//Set Found!
found = true;
}
}
}
如何在没有System.OutOfMemoryException 的情况下读取带有XmlReader 的文件内容字符串?
【问题讨论】:
-
您可能可以使用XmlReader.ReadValueChunk 逐个读取和解码大型 Base64 内容。确保 char 缓冲区的大小允许整个缓冲区完全进行 Base64 解码。由于 Base64 字符始终编码 6 位,因此选择一个缓冲区大小
numB64Chars解码为numBytes字节其中numB64Chars = numBytes * 4/3(= numBytes * 8/6) -
(旁注:注意文档。XmlReader.ReadValueChunk 不保证它会在一次调用中填充缓冲区。而是检查 XmlReader.ReadValueChunk 的返回值以查看它有多少 Base64 字符已读取,如有必要再次调用此方法 - 当然,使用适当调整的参数 - 直到缓冲区完全填满或到达内容末尾)
-
@elgonzo 谢谢。这是一个很好的解决方案。我只搜索了 readelement.... 下次,我必须阅读更多文档。