Advanced - File providers
In this article
-
IWebHostEnvironment exposes the app's content
root
and webroot
asIFileProvider
types. -
Static File Middleware uses File Providers to locate static files.
-
Razor uses File Providers to locate pages and views.
-
.NET Core tooling uses File Providers and glob patterns to specify which files should be published.
File Provider interfaces
-
Obtain file information (IFileInfo).
-
Obtain
directory
information (IDirectoryContents). -
Set up change notifications (using an
IChangeToken
). -
Exists
-
IsDirectory
-
Name
-
Length (in bytes)
-
LastModified date
File Provider implementations
Implementation | Description |
---|---|
Composite File Provider | Used to provide combined access to files and directories from one or more other providers. |
Manifest Embedded File Provider | Used to access files embedded in assemblies. |
Physical File Provider | Used to access the system's physical files. |
Physical File Provider
var provider = new PhysicalFileProvider(applicationRoot);
var contents = provider.GetDirectoryContents(string.Empty);
var filePath = Path.Combine("wwwroot", "js", "site.js");
var fileInfo = provider.GetFileInfo(filePath);
-
provider
is anIFileProvider
. -
contents
is anIDirectoryContents
. -
fileInfo
is anIFileInfo
.
var physicalProvider = _env.ContentRootFileProvider;
Manifest Embedded File Provider
-
Add the
Microsoft.Extensions.FileProviders.Embedded
NuGet package to your project. -
Set the
<GenerateEmbeddedFilesManifest>
property totrue
. Specify the files to embed with<EmbeddedResource>
:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<GenerateEmbeddedFilesManifest>true</GenerateEmbeddedFilesManifest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resource.txt" />
</ItemGroup>
</Project>
var manifestEmbeddedProvider =
new ManifestEmbeddedFileProvider(typeof(Program).Assembly);
-
Specify a relative file path.
-
Scope files to a last modified date.
-
Name the embedded resource containing the embedded file manifest.
Overload | Description |
---|---|
ManifestEmbeddedFileProvider(Assembly, String) |
Accepts an optional root relative path parameter. Specify the root to scope calls to GetDirectoryContents to those resources under the provided path. |
ManifestEmbeddedFileProvider(Assembly, String, DateTimeOffset) |
Accepts an optional root relative path parameter and a lastModified date (DateTimeOffset) parameter. The lastModified date scopes the last modification date for the IFileInfo instances returned by the IFileProvider. |
ManifestEmbeddedFileProvider(Assembly, String, String, DateTimeOffset) |
Accepts an optional root relative path, lastModified date, and manifestName parameters. The manifestName represents the name of the embedded resource containing the manifest. |
Composite File Provider
var physicalProvider = _env.ContentRootFileProvider;
var manifestEmbeddedProvider =
new ManifestEmbeddedFileProvider(typeof(Program).Assembly);
var compositeProvider =
new CompositeFileProvider(physicalProvider, manifestEmbeddedProvider);
services.AddSingleton<IFileProvider>(compositeProvider);
Watch
for changes
-
Accepts a file path string, which can use glob patterns to specify multiple files.
-
Returns an
IChangeToken
. -
HasChanged: A property that can be inspected to determine if a change has occurred.
-
RegisterChangeCallback: Called when changes are detected to the specified path string. Each change token only calls its associated callback in response to a single change. To enable constant monitoring, use a
TaskCompletionSource<TResult>
(shown below) or recreateIChangeToken
instances in response to changes.
private static readonly string _fileFilter = Path.Combine("TextFiles", "*.txt");
public static void Main(string[] args)
{
Console.WriteLine($"Monitoring for changes with filter '{_fileFilter}' (Ctrl + C to quit)...");
while (true)
{
MainAsync().GetAwaiter().GetResult();
}
}
private static async Task MainAsync()
{
var fileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());
IChangeToken token = fileProvider.Watch(_fileFilter);
var tcs = new TaskCompletionSource<object>();
token.RegisterChangeCallback(state =>
((TaskCompletionSource<object>)state).TrySetResult(null), tcs);
await tcs.Task.ConfigureAwait(false);
Console.WriteLine("file changed");
}
Glob patterns
Pattern | Description |
---|---|
directory/file.txt |
Matches a specific file in a specific ```directory```. |
directory/*.txt |
Matches all files with .txt extension in a specific ```directory```. |
directory/*/appsettings.json |
Matches all appsettings.json files in directories exactly one level below the directory folder. |
directory/**/*.txt |
Matches all files with a .txt extension found anywhere under the directory folder. |