因此,通过我的研究,我知道您需要在再次阅读之前"rewind" a stream,或者需要copy a stream。
我无法回放此流,因此我必须复制它。我尝试在下面做,但是当我从任一流中读取时,我最终读取0字节
CopyTo的文档说它“读取了流”。
这个“阅读”是否在最后设置了“读头”,还是我只是做了别的错误?
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();
}
答案 0 :(得分:1)
如果您在此行之后查看调试器中的stream
:
request.InputStream.CopyTo(stream);
您将看到它的位置位于流的末尾。如果您在此行之后重置位置,您将按预期读取数据,假设流不为空:
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();