Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Created January 4, 2020 11:05
Show Gist options
  • Save BananaAcid/629b8511a49526340261ed873e2c5ecd to your computer and use it in GitHub Desktop.
Save BananaAcid/629b8511a49526340261ed873e2c5ecd to your computer and use it in GitHub Desktop.
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