0

I'm trying to send a XML file on request, but I'm getting an error when I'm trying to copy the stream, which I'm loading the file into, to the output stream.

Right now it's working fine if I'm making the request (I use HttpListener btw) from a browser; it shows me my .xml just fine. But I'd also like to be able to download the .xml when I make the request.

Any suggestions?

    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);
    }

The error I'm getting is at input.CopyTo(output); : "Stream does not support reading."

Khaine775
  • 2,715
  • 8
  • 22
  • 51
  • 1
    look at some of the posted answers and comments here http://stackoverflow.com/questions/230128/how-do-i-copy-the-contents-of-one-stream-to-another || http://stackoverflow.com/questions/10664458/memorystream-writetostream-destinationstream-versus-stream-copytostream-desti – MethodMan Nov 25 '14 at 14:39
  • 1
    If you inline `stream` variable you'll get `CopyStream(response.OutputStream, response.OutputStream);` which may help to understand why code does not work. – Alexei Levenkov Nov 25 '14 at 15:54

1 Answers1

2

You probably get the error because the stream input actually is the response.OutputStream, which is an output stream and also makes the source and target of the copy operation the same stream - huh?

Essentially what your code does now (and this is wrong): You save the XML content to the response's output stream (which essentially already sends it to the browser). Then you try to copy the output stream into the output stream. This doesn't work and even if it did - why? You already wrote to the output stream.

You can simplify all this greatly in my opinion as follows:

// 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();
Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139