处理由方法返回的XmlReader的底层MemoryStream

时间:2013-02-05 23:27:06

标签: c#

我有以下方法返回XmlReader

public XmlReader RequestXML(string endpoint)
{
    using (WebClient request = this.PrepareRequest(RestMethod.GET, null))
    {
        byte[] response = request.DownloadData(this.RestUrl + endpoint);
        using (MemoryStream responseStream = new MemoryStream(response))
        {
            XmlReader xReader = XmlReader.Create(responseStream);
            return xReader;
        }
    }
}

但是,当然,这不起作用,因为MemoryStream在调用代码有机会使用XmlReader之前关闭。是否可以返回XmlReader并仍然处置其基础MemoryStream

我考虑过接受一个委托(或Action<XmlReader>)作为我的方法中的第二个参数来完成using内的工作,但这个设计看起来有点尴尬。

另外,I can't just call WebClient.DownloadString()

1 个答案:

答案 0 :(得分:2)

如果有疑问,请使用XmlReaderSettings.CloseInput进行此重载:XmlReader.Create(Stream, XmlReaderSettings),就像这样...

public XmlReader RequestXML(string endpoint)
{
    using (WebClient request = this.PrepareRequest(RestMethod.GET, null))
    {
        byte[] response = request.DownloadData(this.RestUrl + endpoint);
        MemoryStream responseStream = new MemoryStream(response);
        XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
        xmlReaderSettings.CloseInput = true;
        return XmlReader.Create(responseStream, xmlReaderSettings);
    }
}

这样调用RequestXml的代码无需负责处理MemoryStream