create a http server and upload a file in csharp

To create a HTTP server in C#, we can use the HttpListener class, which is available in the System.Net namespace. Here's an example of how to create a simple HTTP server in C#:

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

public class HttpServerExample
{
    public static void Main(string[] args)
    {
        // Create a HttpListener instance
        HttpListener listener = new HttpListener();

        // Add the prefixes to listen to
        listener.Prefixes.Add("http://localhost:8080/");

        // Start the listener
        listener.Start();
        Console.WriteLine("Listening on localhost:8080");

        // Listen for requests
        while (true)
        {
            HttpListenerContext context = listener.GetContext();

            // Handle the request
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.Url);

            // If the request is a POST and has files attached to it, we handle it
            if (request.HttpMethod == "POST" && request.HasEntityBody && request.ContentType.StartsWith("multipart/form-data"))
            {
                // Create a stream reader to read the request's body
                StreamReader reader = new StreamReader(request.InputStream);

                // Read the boundary string from the content type
                string contentType = request.ContentType;
                string boundary = contentType.Substring(contentType.IndexOf("boundary=") + "boundary=".Length);

                // Split the body into its parts using the boundary as a separator
                string[] bodyParts = reader.ReadToEnd().Split(new string[] { boundary }, StringSplitOptions.RemoveEmptyEntries);

                // Loop through the parts and handle each one
                foreach (string part in bodyParts)
                {
                    // If the part is a file, we handle it
                    if (part.Contains("filename=\""))
                    {
                        // Get the name of the file
                        string fileNameStart = part.IndexOf("filename=\"") + "filename=\"".Length;
                        string fileNameEnd = part.IndexOf("\"", fileNameStart);
                        int fileNameLength = fileNameEnd - fileNameStart;
                        string fileName = part.Substring(fileNameStart, fileNameLength);

                        // Get the file content
                        string fileContentStart = part.IndexOf("\r\n\r\n") + "\r\n\r\n".Length;
                        string fileContentEnd = part.IndexOf("\r\n", fileContentStart);
                        int fileContentLength = fileContentEnd - fileContentStart;
                        byte[] fileContent = Encoding.UTF8.GetBytes(part.Substring(fileContentStart, fileContentLength));

                        // Save the file to disk
                        File.WriteAllBytes(fileName, fileContent);

                        Console.WriteLine("File saved: " + fileName);
                    }
                }
            }

            // Send a response back to the client
            string responseString = "Hello, world!";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;
            output.Write(buffer, 0, buffer.Length);
            output.Close();
        }
    }
}
3366 chars
80 lines

This server listens on http://localhost:8080/ and responds to all incoming requests, printing each request to the console. If the request is a POST and has files attached to it, it saves each file to disk.

To upload a file to this server, you can use curl or a similar tool. Here's an example using curl:

curl -X POST -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "file=@/path/to/file" http://localhost:8080/
148 chars
2 lines

This will upload the file located at /path/to/file to the server.

gistlibby LogSnag