.NET Framework Basic read-only HTTP file server (ASP.NET Core)

Download .NET Framework for free

Example

1 - Create an empty folder, it will contain the files created in the next steps.

2 - Create a file named project.json with the following content (adjust the port number and rootDirectory as appropriate):

{
  "dependencies": {
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final"
  },

  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:60000"
  },

  "frameworks": {
    "dnxcore50": { }
  },

  "fileServer": {
    "rootDirectory": "c:\\users\\username\\Documents" 
  }
}

3 - Create a file named Startup.cs with the following code:

using System;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.FileProviders;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.StaticFiles;
using Microsoft.Extensions.Configuration;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        var builder = new ConfigurationBuilder();
        builder.AddJsonFile("project.json");
        var config = builder.Build();
        var rootDirectory = config["fileServer:rootDirectory"];
        Console.WriteLine("File server root directory: " + rootDirectory);

        var fileProvider = new PhysicalFileProvider(rootDirectory);

        var options = new StaticFileOptions();
        options.ServeUnknownFileTypes = true;
        options.FileProvider = fileProvider;
        options.OnPrepareResponse = context =>
        {
            context.Context.Response.ContentType = "application/octet-stream";
            context.Context.Response.Headers.Add(
                "Content-Disposition",
                $"Attachment; filename=\"{context.File.Name}\"");
        };
        
        app.UseStaticFiles(options);
    }
}

4 - Open a command prompt, navigate to the folder and execute:

dnvm use 1.0.0-rc1-final -r coreclr -p
dnu restore

Note: These commands need to be run only once. Use dnvm list to check the actual number of the latest installed version of the core CLR.

5 - Start the server with: dnx web. Files can now be requested at http://localhost:60000/path/to/file.ext.

For simplicity, filenames are assumed to be all ASCII (for the filename part in the Content-Disposition header) and file access errors are not handled.

Basic read-only HTTP file server (HttpListener)