2014-11-25 62 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();