StreamWriter 输出 BaseStream 在前

StreamWriter output BaseStream comes first

我有以下用于 SimpleHttp 服务器的代码:

   using (Stream fs = File.Open(@"C:\Users\Mohamed\Desktop\Hany.jpg", FileMode.Open))
            {
                StreamWriter OutputStream = new StreamWriter(new BufferedStream(someSocket.GetStream()));
                OutputStream.WriteLine("HTTP/1.0 200 OK");
                OutputStream.WriteLine("Content-Type: application/octet-stream");
                OutputStream.WriteLine("Content-Disposition: attachment; filename=Hany.jpg");
                OutputStream.WriteLine("Content-Length: " + img.Length);
                OutputStream.WriteLine("Connection: close");
                OutputStream.WriteLine(""); // this terminates the HTTP headers

                fs.CopyTo(OutputStream.BaseStream);
                OutputStream.Flush();
                //OutputStream.BaseStream.Flush();
            }

问题是,当我看到输出 http 响应时,header 位于文本末尾,而来自 BaseStream 的图像二进制文件甚至在 header 之前就排在第一位。输出示例是(当然我删除了图像的长字节):

    ä3ST)ëî!ðDFYLQ>qâ:oÂÀó?ÿÙHTTP/1.0 200 OK
    Content-Type: image/png
    Connection: close

我想要的是颠倒顺序,把header放在最上面,得到的是这样的:

    HTTP/1.0 200 OK
    Content-Type: image/png
    Connection: close
    ä3ST)ëî!ðDFYLQ>qâ:oÂÀó?ÿÙT4ñ®KÛ'`ÃGKs\CGÔ«¾+L»ê±?0Íse3rïÁå·>"ܼ;®N¦Ãõ5¨LZµL¯

在流写入器或 BaseStream 上使用刷新并不重要。 任何帮助!

我认为问题是由调用 CopyTo 和传递 BaseStream 引起的。它可能会绕过尚未刷新数据的 StreamWriter。

不应使用 BaseStream 进行写入。必须使用 StreamWriter。

using (StreamWriter outputStream = new StreamWriter(new BufferedStream(someSocket.GetStream())))
 {
    outputStream.WriteLine("HTTP/1.0 200 OK");
    outputStream.WriteLine("Content-Type: application/octet-stream");
    outputStream.WriteLine("Content-Disposition: attachment; filename=Hany.jpg");
    outputStream.WriteLine("Content-Length: " + img.Length);
    outputStream.WriteLine("Connection: close");
    outputStream.WriteLine(""); // this terminates the HTTP headers

    string imageContent = Convert.ToBase64String(File.ReadAllBytes(@"C:\Users\Mohamed\Desktop\Hany.jpg"));
    outputStream.Write(imageContent);
    outputStream.Flush();
}

谢谢 Kzrystof,我接受了你的提示,现在可以在使用 copyTo 之前刷新 StreamWriter,但是我真的不知道这样做是否正确?你怎么看?

  using (Stream fs = File.Open(@"C:\Users\Mohamed\Desktop\Hany.jpg", FileMode.Open))
        {
            StreamWriter OutputStream = new StreamWriter(new BufferedStream(someSocket.GetStream()));
            OutputStream.WriteLine("HTTP/1.0 200 OK");
            OutputStream.WriteLine("Content-Type: application/octet-stream");
            OutputStream.WriteLine("Content-Disposition: attachment; filename=Hany.jpg");
            OutputStream.WriteLine("Content-Length: " + img.Length);
            OutputStream.WriteLine("Connection: close");
            OutputStream.WriteLine(""); // this terminates the HTTP headers
            OutputStream.Flush();

            fs.CopyTo(OutputStream.BaseStream);
            OutputStream.BaseStream.Flush();
            OutputStream.Flush();
        }