2014-11-25 125 views
0

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

现在它工作正常,如果我从浏览器发出请求(我使用HttpListener btw);它显示我的.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);:“流不支持读取。”

+1

看看这里的一些张贴答案和注释的http://stackoverflow.com/questions/230128/how-do-i-复制一个流的内容到另一个|| http://stackoverflow.com/questions/10664458/memorystream-writetostream-destinationstream-versus-stream-copytostream-desti – MethodMan 2014-11-25 14:39:03

+1

如果你内嵌'stream'变量,你会得到'CopyStream(response.OutputStream,response.OutputStream);'这可能有助于理解为什么代码不起作用。 – 2014-11-25 15:54:37

回答

2

你可能会得到错误,因为流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();