I have the below code for a SimpleHttp Server:
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();
}
The problem is when I see the output http response the headers are in the end of the text and the image binary from the BaseStream comes first even before the header. Sample of the output is(of course I removed the long bytes for the image):
ä3ST)ëî!ðDFYLQ>qâ:oÂÀó?ÿÙHTTP/1.0 200 OK
Content-Type: image/png
Connection: close
What I want is to reverse the order and get the headers on top, to get is something like this:
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¯
Using flush on the stream writer or on the BaseStream does not matter. Any Help!
Thank you Kzrystof, I took your hint and it works now with flushing the StreamWriter before using copyTo, however I don't really know if this is correct thing to do? What do you think about it?
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();
}