【问题标题】:Send XML file on request根据请求发送 XML 文件
【发布时间】:2014-11-25 14:34:00
【问题描述】:

我正在尝试根据请求发送 XML 文件,但是当我尝试将要加载文件的流复制到输出流时出现错误。

现在如果我从浏览器发出请求(我使用 HttpListener 顺便说一句),它工作正常;它向我展示了我的 .xml 就好了。但我也希望能够在我提出请求时下载 .xml。

有什么建议吗?

    string xString = @"C:\Src\Capabilities.xml";
    XDocument capabilities = XDocument.Load(xString);
    Stream stream = response.OutputStream;
    response.ContentType = "text/xml";

    capabilities.Save(stream);
    CopyStream(stream, response.OutputStream);

    stream.Close();


    public static void CopyStream(Stream input, Stream output)
    {
        input.CopyTo(output);
    }

我得到的错误是input.CopyTo(output);:“流不支持阅读。”

【问题讨论】:

标签: c# xml


【解决方案1】:

您可能会收到错误,因为流 input 实际上是 response.OutputStream,它是一个输出流,并且也使复制操作的源和目标成为同一个流 - 嗯?

基本上你的代码现在做了什么(这是错误的):你将 XML 内容保存到响应的输出流(基本上已经将它发送到浏览器)。然后您尝试将输出流复制到输出流中。这不起作用,即使它起作用了 - 为什么?您已经写入了输出流。

在我看来,您可以将这一切大大简化如下:

// Read the XML text into a variable - why use XDocument at all?
string xString = @"C:\Src\Capabilities.xml";
string xmlText = File.ReadAllText(xString);

// Create an UTF8 byte buffer from it (assuming UTF8 is the desired encoding)
byte[] xmlBuffer = Encoding.UTF8.GetBytes(xmlText);

// Write the UTF8 byte buffer to the response stream
Stream stream = response.OutputStream;
response.ContentType = "text/xml";
response.ContentEncoding = Encoding.UTF8;
stream.Write(xmlBuffer, 0, xmlBuffer.Length);

// Done
stream.Close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多