joydip_kanjilal
Contributor

How to use File Providers in ASP.Net Core

how-to
Sep 24, 20184 mins
Microsoft .NETSmall and Medium BusinessSoftware Development

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

file folders / library / archive / repository
Credit: 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. 

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author