c# - 保存 webrequest 返回的流对象

标签 c#

我有一段代码可以从站点检索 XML 文件,所以我按如下方式操作:

WebRequest request = WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "text/xml";

using (WebResponse webResponse = request.GetResponse())
{
    using (Stream responseStream = webResponse.GetResponseStream())
    {
       if (responseStream != null)
        {
            reportXML = XDocument.Load(responseStream.ToString());
        }
    }
    using (XmlWriter writer = XmlWriter.Create(@"C:\Retrieved.xml"))
    {
        reportXML.Save(writer);
    }
 }

但是我调试了应用程序,似乎我失去了这行代码中的所有内容,所以我没有什么可以保存的了。

Stream responseStream = webResponse.GetResponseStream())

知道为什么会这样吗?

如果我调查这个对象,我会看到这个:

Length = 'responseStream.Length' threw an exception of type 'System.NotSupportedException'

错误如下:

Could not find file 'C:\Documents and Settings\user\My Documents\Visual Studio 2010\Projects\Proto\App\bin\Debug\System.Net.ConnectStream'.

最佳答案

问题是:

reportXML = XDocument.Load(responseStream.ToString());

像这样在流上调用 ToString() 几乎永远不会给您任何有用的东西。如果您只想加载流的内容,请去掉 ToString 调用:

reportXML = XDocument.Load(responseStream);

或者,如果您真的只想将它保存到磁盘,只需使用Stream.CopyTo即可。并且首先不要费心将其解析为 XML。

关于c# - 保存 webrequest 返回的流对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567254/

相关文章:

c# - 在 c# 中读取 excel 文件时, 'microsoft.ace.oledb.12.0' 提供程序未在本地计算机上注册

c# - 安装项目后出现C#错误

c# - CultureInfo 和 ISO 639-3

c# - 属性网格 > 如何刷新主属性

c# - 从一个密码派生多个 key 是否安全?

c# - 如何从方法返回 LINQ 对象?

c# - 条目(XAML 表单)对象引用仅对 UWP 应用程序为 null

c# - 在 LINQ to Entities 上调用自定义(格式化)方法

c# - 何时检查对象的状态,一般 OOP,C# 中的示例

c# - 在 HTTP GET 中绑定(bind) en-GB 日期