IFileProvider

File providers are a new way to access file in .NET Core applications. It's yet another abstraction in this framework and is a buffer between physical localization and place of file or folder in project's tree. It provides organized and restricted access to files or assemblies defined in a scope.

IFileProvider interface has three implementations:

PhysicalFileProvider

Provides access to the physical file system. Directory path given at instantiating becomes the base path for all requests made to this provider, hence it also protects from accessing anything outside assigned scope. PhysicalFileProvider can be instantiated directly in an app, or by requesting an IFileProvider in a Controller or service's constructor through DI. For more details, please visit MSDN.

You can easily iterate through the directory by using foreach loop:


[Controller]
IFileProvider fileprovider = new PhysicalFileProvider(applicationRoot);
var contents = fileProvider.GetDirectoryContents("");
return View(contents);

...
  
[index.cshtml]
@foreach (IFileInfo item in contents) {
  if (item.IsDirectory) {
    <li><strong>@item.Name</strong></li>
  }
  else {
    <li>@item.Name - @item.Length bytes</li>
  }
}

EmbeddedFileProvider

Provides access to files embedded in assemblies. You can embed files into assembly with the <EmbeddedResource> element in .csproj file:


<ItemGroup>
  <EmbeddedResource Include="Resource.txt;**\*.js" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
  <Content Update="wwwroot\*\*.txt;Views\**\*;Areas\**\Views;appsettings.json;web.config">
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  </Content>
</ItemGroup>

When specifying paths and files you can use globbing patterns. So above, consecutive lines mean:

  • bin\** – all files under bin directory
  • **\*.xproj – all files under base directory with .xproj extension
  • Areas\**\Views – matches all Views directories under Areas directory
  • wwwroot\*\*.txt – all txt files exactly one level under wwwroot directory

CompositeFileProvider

Provides access via single inerface to one or more file providers, that can be of different implementation of IFileProvider. When instantiating, pass those providers instances to the constructor.


var compositeProvider = new CompositeFileProvider(physicalProvider, embeddedProvider);

FileProvider as a Share Point

FileProviders can be used a "Share Point" and thus provide easy access to files stored externaly for the sake of bandwidth and space. By the time of writing this blog post I have not found any example nor provided any of my own.

Leave a Reply

Your email address will not be published. Required fields are marked *