Dario Benevento Dario Benevento - 4 years ago 188
C# Question

Webserver response for image in C#

I'm trying to develop a little program in C# as UWP that will be able to send a response over http as HTML page. Actually I'm able to answer with a text stream with this code:

using (var output = args.Socket.OutputStream)
{
using (var response = output.AsStreamForWrite())
{
var html = Encoding.UTF8.GetBytes(htmlResponse);
using (var bodyStream = new MemoryStream(html))
{
var header = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\nConnection: close\r\n\r\n";
var headerArray = Encoding.UTF8.GetBytes(header);
await response.WriteAsync(headerArray, 0, headerArray.Length);
await bodyStream.CopyToAsync(response);
await response.FlushAsync();
}
}
}


And the response is

HTTP/1.1 200 OK
Content-Length: {bodyStream.Length}
Connection: close


But when I try to answer with a jpeg image or png image, the answer is not interpreted from browser. I tryed to convert the image in byte array, stream, Base64 but nothing will do the job.
How can I do that?

Thanx a lot

Answer Source

I think you only need to add a header with the mime type: image/jpeg and try to response with the types you listed above.(byte array, stream, Base64)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download