C# 根据请求发送XML文件
我试图根据请求发送一个XML文件,但是当我试图将文件加载到的流复制到输出流时,我遇到了一个错误 现在,如果我从浏览器发出请求(我使用HttpListener,顺便说一句),它工作正常;它很好地显示了我的.xml。但我也希望在发出请求时能够下载.xml 有什么建议吗C# 根据请求发送XML文件,c#,xml,C#,Xml,我试图根据请求发送一个XML文件,但是当我试图将文件加载到的流复制到输出流时,我遇到了一个错误 现在,如果我从浏览器发出请求(我使用HttpListener,顺便说一句),它工作正常;它很好地显示了我的.xml。但我也希望在发出请求时能够下载.xml 有什么建议吗 string xString = @"C:\Src\Capabilities.xml"; XDocument capabilities = XDocument.Load(xString); Stream str
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(输出)
:“流不支持读取。”您可能会收到错误,因为流输入
实际上是响应。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();
查看此处发布的一些答案和评论| |如果您内联
stream
变量,您将获得CopyStream(response.OutputStream,response.OutputStream)代码>这可能有助于理解代码不起作用的原因。