How to use File Providers in ASP.Net Core

Take advantage of File Providers in ASP.Net Core to retrieve information about files and directories and interact with the physical file system

How to use File Providers in ASP.Net Core
nikada / Getty Images

File Providers in ASP.Net Core provide a layer of abstraction on the file system, allowing us to easily obtain file and directory information, watch for changes, and of course access physical files. This article examines how we can work with file providers in ASP.Net Core.

File Provider abstractions

The file providers implement the IFileProvider interface. There are three implementations of IFileProvider: Physical, Embedded, and Composite. The IFileProvider is the main interface that exposes the necessary methods to retrieve file information (using the IFileInfo interface) and directory information (using the IDirectoryContents interface). To set up change notifications, you can take advantage of the IChangeToken interface.

Below I’ve listed each file provider class and its purpose. Each of these providers implements the IFileProvider interface.

  • PhysicalFileProvider—used to provide access to the physical file system
  • EmbeddedFileProvider—used to access files inside the assemblies
  • CompositeFileProvider—used to provide combined access; i.e., a single interface used to work with files from multiple providers

Use PhysicalFileProvider in ASP.Net Core

In this section we will explore how we can take advantage of the PhysicalFileProvider class in ASP.Net Core. First off, follow the steps outlined below to create an ASP.Net Core application in Visual Studio.

  1. Open Visual Studio 2017
  2. Click on File > New > Project
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates
  4. Specify a name for the project
  5. Click OK
  6. Select “API” in the “New .Net Core Web Application…” window
  7. Select the version of ASP.Net Core you would like to use from the drop-down list at the top
  8. Uncheck “Enable Docker Support” and “Configure for HTTPS”
  9. Select “No Authentication” as we won’t be using authentication here
  10. Click OK

This will create a new ASP.Net Core project. The following code snippet illustrates how you can inject a PhysicalFileProvider object as a dependency using the ConfigureServices method of the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
            services.AddSingleton<IFileProvider>(physicalProvider);
        }

Next, edit the ValuesController (which we will use here for simplicity) and write the following code.

public class ValuesController : ControllerBase
 {
        private readonly IFileProvider _fileProvider;
        public ValuesController(IFileProvider fileProvider)
        {
            _fileProvider = fileProvider;
        }
     //Other methods
  }

Note how dependency has been injected using the argument constructor. Below is the method that accesses the current directory and then uses the IFileInfo interface to retrieve the names of all of the files the directory contains. The file names are then returned as a generic list of string objects.

[HttpGet]
        public ActionResult<List<string>> Get()
        {
            List<string> lst = new List<string>();
            var contents = _fileProvider.GetDirectoryContents(“”);
            foreach(IFileInfo fileInfo in contents)
            {
                lst.Add(fileInfo.Name);
            }
            return lst;
        } 

The following code listing shows the complete code of the ValuesController class.

[Route(“api/[controller]”)]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IFileProvider _fileProvider;
        public ValuesController(IFileProvider fileProvider)
        {
            _fileProvider = fileProvider;
        }
        [HttpGet]
        public ActionResult<List<string>> Get()
        {
            List<string> lst = new List<string>();
            var contents = _fileProvider.GetDirectoryContents(“”);
            foreach(IFileInfo fileInfo in contents)
            {
                lst.Add(fileInfo.Name);
            }
            return lst;
        }      
    }    

Use CompositeFileProvider in ASP.Net Core

The CompositeFileProvider class combines one or more IFileProvider instances and exposes a single interface that can be used to work with multiple providers. Note that when creating a CompositeFileProvider, you should pass one or more IFileProvider instances to the constructor of the CompositeFileProvider class. Here is an example that illustrates this.

var physicalProvider = _env.ContentRootFileProvider;
var embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
var compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);

Use EmbeddedFileProvider in ASP.Net Core

The EmbeddedFileProvider class is used to access files that are embedded in assemblies. The following code snippet illustrates how EmbeddedFileProvider can be injected as a dependency in ASP.Net Core.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            IFileProvider embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
            services.AddSingleton<IFileProvider>(embeddedProvider);
        }

You can take advantage of File Providers to retrieve information about files and directories and also set up change notifications in your .Net Core applications. And if your ASP.Net Core application needs access to the file system, you can take advantage of dependency injection to inject an instance of the file provider you would like to use. 

Copyright © 2018 IDG Communications, Inc.

How to choose a low-code development platform