Introduction
The file system can be accessed through the use of File Providers in ASP.NET Core. In other words, we can say that "File Provider is an abstraction over file system". The file providers use IFileProvider interface and it has methods to get file information, directory information, and also, the setup change notification.
The IFileInfo is used to get the file information, and it provides the methods and properties for individual files and directories. The IDirectoryContents interface is used to retrieve directory's content in the file provider. The IChangeToken interface propagates notifications that a change has occurred.
There are three types of IFileProvider Implementations -
- Physical File Provider - it is used to access the actual or physical file of the system
- Embedded File Provider - it is used to access files that are embedded in assemblies
- Composite File Provider - it is used to provide combine access to the files from one or more providers.
PhysicalFileProvider
The PhysicalFileProvider wraps the System.IO. File type and provides the access to the physical file system. It is able to access all the paths to a directory and sub-directory. It has limited access to some of the directory. We can instantiate a PhysicalFileProvider provider from the ConfigureServices service method of startup class and we can inject it as a dependency in controller constructor.
In the following code, I have created PhysicalFileProvider object and injected as dependency.
ConfigureServices method of Startup Class
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
-
- services.AddSingleton<IFileProvider>(physicalProvider);
- }
HomeController.cs
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.FileProviders;
-
- public class HomeController : Controller
- {
- private readonly IFileProvider _fileProvider;
- public HomeController(IFileProvider fileProvider)
- {
- _fileProvider = fileProvider;
- }
- [Route("home/index")]
- public IActionResult Index()
- {
- var contents = _fileProvider.GetDirectoryContents("");
- return View(contents);
- }
- }
Index.cshtml- @using Microsoft.Extensions.FileProviders
- @model IDirectoryContents
-
- <h2>Folder Contents</h2>
-
- <ul>
- @foreach (IFileInfo item in Model)
- {
- if (item.IsDirectory)
- {
- <li><strong>@item.Name</strong> - Directory</li>
- }
- else
- {
- <li><strong>@item.Name</strong> - @item.PhysicalPath </li>
- }
- }
- </ul>
Output
EmbeddedFileProvider
This provider is used to access the files that are embedded in assemblies. We can embed files in assembly using "EmbeddedResource" element in .csproj file (with Visual Studio 2017). We can also specify the files using globbing patterns.
Here, we need to create EmbeddedFileProvider object and inject it as dependency. The Controller and View code remain same.
- IFileProvider embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
- services.AddSingleton<IFileProvider>(embeddedProvider);
CompositeFileProvider
It combines two or more IFileProvider instances and exposing a single interface for working with files. In the following example I have created CompositeFileProvider and passed two IFileProvider instances (physical and embedded providers) to its constructor. As a result, we can get both type provider of files.
- IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
- IFileProvider embeddedProvider = new EmbeddedFileProvider(Assembly.GetEntryAssembly());
- IFileProvider compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);
-
- services.AddSingleton<IFileProvider>(compositeProvider);
Output
Watching on files or directories change
The Watch method of IFileProvider provides the way to watch one or more directories and files for changes. This method accepts path as string. We can also specify the multiple file or directories path using globbing patterns. This method returns IChangeToken. The IChangeToken exposes "HasChanged" property which used to inspection and RegisterChangeCallback method is called when changes are detected. For continuously monitoring, we need to use TaskCompletionSource.
In the following example, I have created a console application that watches on "watchFil.txt" and console application displays message when this text file is modified.
- using System;
- using System.IO;
- using System.Threading.Tasks;
- using Microsoft.Extensions.FileProviders;
- using Microsoft.Extensions.Primitives;
-
- namespace ConsoleApplication
- {
- public class Program
- {
- private static PhysicalFileProvider _fileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
- public static void Main(string[] args)
- {
- while (true)
- {
- MainAsync().GetAwaiter().GetResult();
- }
- }
- private static async Task MainAsync()
- {
- IChangeToken token = _fileProvider.Watch("WatchFile.txt");
- var source = new TaskCompletionSource<object>();
- token.RegisterChangeCallback(state =>
- ((TaskCompletionSource<object>)state).TrySetResult(null), source);
- await source.Task.ConfigureAwait(false);
- Console.WriteLine("File changed - WatchFile.txt");
- }
- }
- }
Output
Summary
Using the IFileProvider, we can access the file system in ASP.NET Core application and using file watcher, and we are able to track file changes.