using System; using System.Net; class Program { static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); Console.WriteLine("Listening for requests on http://localhost:8080/"); while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; string responseString = "Hello World!"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } } }
using System; using System.Net; using System.IO; class Program { static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); Console.WriteLine("Listening for requests on http://localhost:8080/"); while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; if (request.HttpMethod == "POST" && request.ContentType.StartsWith("multipart/form-data")) { string filename = ""; foreach (string header in request.Headers) { if (header.StartsWith("Content-Disposition")) { int startIndex = header.IndexOf("filename=") + 10; int endIndex = header.LastIndexOf("\""); filename = header.Substring(startIndex, endIndex - startIndex); filename = Path.GetFileName(filename); } } byte[] buffer = new byte[request.ContentLength64]; int bytesRead = request.InputStream.Read(buffer, 0, buffer.Length); using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write)) { fs.Write(buffer, 0, bytesRead); } HttpListenerResponse response = context.Response; response.StatusCode = (int)HttpStatusCode.OK; response.StatusDescription = "OK"; response.Close(); } else { HttpListenerResponse response = context.Response; response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; response.StatusDescription = "Method Not Allowed"; response.Close(); } } } }This code sets up an HttpListener to listen for incoming POST requests with a "multipart/form-data" content type. If such a request is received, the program reads the uploaded file from the request InputStream and saves it to disk with the same name as it was uploaded with. Finally, the program sends a 200 OK response back to the client. If the incoming request does not meet these criteria, the program sends a 405 Method Not Allowed response back to the client. Package library: System.NET.HttpListener is part of the .NET Framework Class Library.