簡體   English   中英

XmlReader-如何在沒有System.OutOfMemoryException的情況下讀取元素中的很長的字符串

[英]XmlReader - How to read very long string in element without System.OutOfMemoryException

我必須讀取從API返回的XML元素中的文件內容Base64字符串。

我的問題是此字符串可能很長,具體取決於文件大小。

最初,我使用XmlDocument讀取XML。 現在,當XML太大時,我使用XmlReader來避免System.OutOfMemoryException

但是我在讀取字符串時也收到了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.ReadElementContentAsBase64(Byte[] buffer, Int32 index, Int32 count)可以使用XmlReader.ReadElementContentAsBase64(Byte[] buffer, Int32 index, Int32 count) 此方法允許以塊的形式讀取和解碼XML元素的Base64元素內容,從而避免大型元素出現OutOfMemoryException

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

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);

演示在這里擺弄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM