0

So, through my research, I know you need to either "rewind" a stream before you read from it again, or you need to copy a stream.

I can't rewind this stream, so I must make a copy of it. I tried to do it below, but when I read from either stream, I end up reading 0 bytes

The documentation for CopyTo says that it "reads the stream".

Does this "reading" set the "read head" at the end, or am I just doing something else wrong?

    public static void ListenerCallback(IAsyncResult result)
    {
        HttpListener listener = (HttpListener)result.AsyncState;
        HttpListenerContext context = listener.EndGetContext(result);
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;
        System.IO.Stream stream = new System.IO.MemoryStream();
        request.InputStream.CopyTo(stream);
        StreamReader reader = new StreamReader(stream);
        var res = reader.ReadToEnd(); //I should be seeing output here
        reader.Close();

        Console.WriteLine(res);
        NameValueCollection coll = HttpUtility.ParseQueryString(res);

        using (var outp = File.OpenWrite("output.pptx")) //This file should have data in it
        {
            request.InputStream.CopyTo(outp); 
        }

        response.StatusCode = 200;
        response.ContentType = "text/html";
        using (StreamWriter writer = new StreamWriter(context.Response.OutputStream, Encoding.UTF8))
            writer.WriteLine("File Uploaded");
        response.Close();
        stream.Close();
        request.InputStream.Close();

    }
Community
  • 1
  • 1

1 Answers1

1

If you look at stream in the debugger after this line:

request.InputStream.CopyTo(stream);

You will see that its position is at the end of the stream. If you reset the position after this line you will read data as expected, assuming the stream is not empty:

request.InputStream.CopyTo(stream);
stream.Position = 0;    // Reset the position to the beginning
StreamReader reader = new StreamReader(stream);
var res = reader.ReadToEnd(); //I should be seeing output here
reader.Close();
Slippery Pete
  • 3,051
  • 1
  • 13
  • 15
  • Also, it looks like the original stream I made the copy from moves to the end as well. –  Aug 21 '14 at 17:40