所以,通过我的研究,我知道你需要在再次读取之前"倒带"一个流,或者你需要复制一个流。
我不能倒带这个流,所以我必须复制它。我试着在下面这样做,但是当我从任何一个流中读取时,我最终读取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();
}
如果您在调试器中查看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();