ASP.NET Core 2.0 File Providers

Problem

How to access directory and file information in ASP.NET Core, ensuring restricted access to file system.

Solution

Starting from an empty project, amend the Startup class.

  1. public void ConfigureServices(  
  2.        IServiceCollection services)  
  3.    {  
  4.        services.AddSingleton<IFileProvider>(  
  5.            new PhysicalFileProvider(Directory.GetCurrentDirectory()));  
  6.    }  
  7.   
  8.    public void Configure(  
  9.        IApplicationBuilder app,  
  10.        IHostingEnvironment env)  
  11.    {  
  12.        app.UseHelloFileProvider();  
  13.    } 

Create a middle to read contents of directory.

You could also read a particular file’s contents.

Discussion

ASP.NET Core provides the encapsulation of System.IO.File type in order to limit the access to file system via PhysicalFileProvider type, which is an implementation of IFileProvider.

IFileProvider can be configured as a service (in Startup) and then, injected as a dependency in middleware, controllers etc. This keeps the configuration of file access (e.g. the directory to access) in one place, at the application start-up.

IFileProvider has two important methods,

  • GetDirectoryContents: returns IDirectoryContents. This can be used to iterate over files/folders in a directory.
  • GetFileInfo: returns IFileInfo. This can be used to read the file via its CreateReadStream

Source Code

GitHub