Serve static files outside wwwroot, but handle PhysicalFileProvider when directory does not exist

回眸只為那壹抹淺笑 提交于 2019-12-05 09:53:01

Exception thrown by PhysicalFileProvider:

System.ArgumentException: The directory name D:\Daten7\ is invalid.
Parameter name: path
   at System.IO.FileSystemWatcher..ctor(String path, String filter)
   at System.IO.FileSystemWatcher..ctor(String path)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider.CreateFileWatcher(String root)
   at Microsoft.Extensions.FileProviders.PhysicalFileProvider..ctor(String root)
   at WebApplication1.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

In Startup.cs replace PhysicalFileProvider with PhysicalFileProvider2. Please find source code of PhysicalFileProvider2 below.

Detailed Description of PhysicalFileProvider2

Class PhysicalFileProvider of ASP.Net core insists that directory given as argument to constructor already exists on startup and if it not exists refuses to start up properly

I wrote class PhysicalFileProvider2 which can be used instead. It can be instantiated even if the directory does not exist. But on first invocation of any of its method the directory is created if it not already exists. Now startup properly works and users can add files to directory, which then are properly served.

public class PhysicalFileProvider2 : IFileProvider
{
    private string root;
    private PhysicalFileProvider physicalFileProvider;

    public PhysicalFileProvider2(string root)
    {
        this.root = root;
    }

    private PhysicalFileProvider GetPhysicalFileProvider()
    {
        if (!File.Exists(root))
        {
            Directory.CreateDirectory(root);
        }
        if (physicalFileProvider == null)
        {
            physicalFileProvider = new PhysicalFileProvider(root);
        }
        return physicalFileProvider;
    }

    public IDirectoryContents GetDirectoryContents(string subpath)
    {
        return GetPhysicalFileProvider().GetDirectoryContents(subpath);
    }

    public IFileInfo GetFileInfo(string subpath)
    {
        return GetPhysicalFileProvider().GetFileInfo(subpath);
    }

    public IChangeToken Watch(string filter)
    {
        return GetPhysicalFileProvider().Watch(filter);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!