XmlReader - 如何在没有 System.OutOfMemoryException 的情况下读取元素中很长的字符串 [英] XmlReader - How to read very long string in element without System.OutOfMemoryException

查看:20
本文介绍了XmlReader - 如何在没有 System.OutOfMemoryException 的情况下读取元素中很长的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须读取从 API 返回的 XML 元素中的文件内容 Base64 字符串.

I have to read a file content Base64 string in an element of XML that is returned from an API.

我的问题是这个字符串可能很长,这取决于文件大小.

My problem is this string can be very long, depending on file size.

起初,我使用XmlDocument 来读取XML.现在我使用 XmlReader 来避免System.OutOfMemoryException 当 XML 太大时.

At first, I used XmlDocument to read XML. Now I use XmlReader to avoid System.OutOfMemoryException when XML is too large.

但是当我读取字符串时,也会收到一个 System.OutOfMemoryException.字符串太长了,我猜.

But I when I read the string, receive a System.OutOfMemoryException too. The string is too long, I guess.

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 读取文件内容字符串?

How can I read file content string with XmlReader without System.OutOfMemoryException?

推荐答案

您可以使用 XmlReader.ReadElementContentAsBase64(Byte[] buffer, Int32 index, Int32 count) 用于此目的.此方法允许以块的形式读取和解码 XML 元素的 Base64 元素内容,从而避免大元素的 OutOfMemoryException.

例如,您可以引入以下扩展方法:

For instance, you could introduce the following extension methods:

public static class XmlReaderExtensions
{
    public static bool ReadToAndCopyBase64ElementContentsToFile(this XmlReader reader, string localName, string namespaceURI, string path)
    {
        if (!reader.ReadToFollowing(localName, namespaceURI))
            return false;
        return reader.CopyBase64ElementContentsToFile(path);
    }

    public static bool CopyBase64ElementContentsToFile(this XmlReader reader, string path)
    {
        using (var stream = File.Create(path))
        {
            byte[] buffer = new byte[8192];
            int readBytes = 0;

            while ((readBytes = reader.ReadElementContentAsBase64(buffer, 0, buffer.Length)) > 0)
            {
                stream.Write(buffer, 0, readBytes);
            }
        }
        return true;
    }
}

然后做:

var path = Path.Combine(savepath, file.name);
var found = reader.ReadToAndCopyBase64ElementContentsToFile("content", "", path);

演示小提琴 此处.

这篇关于XmlReader - 如何在没有 System.OutOfMemoryException 的情况下读取元素中很长的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆