create a http server and upload a file and return a binary response in csharp

To create an HTTP server in C#, we will use the HttpListener class. Here is an example code to create an HTTP server and handle file uploads:

main.cs
using System;
using System.Net;
using System.IO;

class HttpServer
{
    static void Main(string[] args)
    {
        // Create an HttpListener to listen for requests
        HttpListener listener = new HttpListener();
        listener.Prefixes.Add("http://localhost:8000/"); // specify your url here
        listener.Start();

        while (true) // run the server indefinitely
        {
            // Wait for a request to come in
            HttpListenerContext context = listener.GetContext();

            if (context.Request.HttpMethod == "POST" && context.Request.HasEntityBody) // check if it's a POST request with a body
            {
                // Get the file data from the request body
                StreamReader reader = new StreamReader(context.Request.InputStream);
                string fileContent = reader.ReadToEnd();

                // Process the file data as needed

                // Return a binary response
                byte[] responseBytes = GetBinaryResponse();
                context.Response.ContentType = "application/octet-stream"; // set the content type to binary
                context.Response.ContentLength64 = responseBytes.Length;
                context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);
            }
            else // return a 404 error for other requests
            {
                context.Response.StatusCode = 404;
                context.Response.Close();
            }
        }
    }

    static byte[] GetBinaryResponse()
    {
        // Return some binary data as an example
        return new byte[]{0x12, 0x34, 0x56, 0x78, 0x90};
    }
}
1648 chars
47 lines

In this example code, we create an HTTP server that listens for requests on http://localhost:8000/. When a POST request with a body comes in, we read the file data from the request body, do some processing as needed, and then return a binary response as an example. Note that in this example, we return a fixed binary data as an example, but you can modify the GetBinaryResponse function to return any binary data that you want.

gistlibby LogSnag