OWIN: Serving static files from an external directory

I am working on an application with a self-hosted OWIN server where the UI is running in an embedded browser and the backend part of the application is implemented using WebApi. When I generate files in the backend, I store them in a subfolder of the application (called “uploads”) configure my application so that files from this folder are served statically:

appBuilder.UseStaticFiles("/uploads");

It all worked fine until an installer was created for the application which installed it in c:\Program Files. Unfortunately, the application is not able to write to the uploads subfolder, so it broke this type of functionality. Obviously, the solution is to be a good Windows citizen and store files created by the application in the LocalAppData directory e.g. instead of using:

Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "uploads")

use:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"MyCompany\uploads")

This solves the issue writing to the folder. All that is now missing is to tell OWIN to serve files from this folder whether the “/uploads” virtual path is accessed:

var staticFilesOptions = new StaticFileOptions();
staticFilesOptions.RequestPath = new PathString("/uploads");
var uploadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"MyCompany\uploads");
Directory.CreateDirectory(uploadPath);
staticFilesOptions.FileSystem = new PhysicalFileSystem(uploadPath);
appBuilder.UseStaticFiles(staticFilesOptions);

Note that the folder needs to exist before you use UseStaticFiles hence the Directory.CreateDirectory call.