Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Super simple c# file server - works with https://www.cs-script.net/
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Net;
namespace SimplestHttpFileServer
{
class Program
{
static void Main(string[] args)
{
HttpListener server = new HttpListener();
server.Prefixes.Add("http://localhost:8080/");
server.Start();
Console.WriteLine("Server started ...");
while (true)
{
HttpListenerContext context = server.GetContext();
Task.Run( async () => {
HttpListenerResponse response = context.Response;
HttpListenerRequest request = context.Request;
//test parallel calls : await Task.Delay(TimeSpan.FromSeconds(5));
string pagePath = Directory.GetCurrentDirectory() + (request.Url.LocalPath == "/" ? @"\index.html" : request.Url.LocalPath);
string html = "";
try {
// pagePath seems to be resolved dynamically - no need for any traversal stuff (`/../` or `/./`)
html = new StreamReader(pagePath).ReadToEnd();
Console.WriteLine("200 " + request.HttpMethod + " " + request.Url.LocalPath);
}
catch(Exception ex) {
if (ex is System.IO.FileNotFoundException || ex is System.IO.DirectoryNotFoundException) {
response.StatusCode = (int)HttpStatusCode.NotFound;
response.StatusDescription = "404";
html = "Not found";
Console.WriteLine("404 " + request.HttpMethod + " " + request.Url.LocalPath);
}
else {
response.StatusCode = (int) HttpStatusCode.InternalServerError;
response.StatusDescription = "500";
html = "Internal Server Error: " + ex.Message;
Console.WriteLine("500 " + request.HttpMethod + " " + request.Url.LocalPath + " --(" + ex.Message + ")");
}
}
byte[] buffer = Encoding.UTF8.GetBytes(html);
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close();
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment