File Provider abstraction File Providers are a layer of abstraction on top of the file system. Its main interface is IFileProvider. IFileProvider exposes methods for obtaining file information (IFileInfo), directory information (IDirectoryContents), and setting change notifications (by using an IChangeToken).
The IFileInfo interface provides methods and properties for manipulating individual files and directories. It has two boolean properties, Exists and IsDirectory, and two properties for two profiles, Name and Length (per byte), and also includes a LastModified date property. You can also read the file contents via the CreateReadStream method.
File Provider implementation There are three implementations of the IFileProvider to choose from: physical, embedded, and composite. The physical type is used to access files in the actual system. Embedded is used to access files embedded in an assembly. The compound type is a combination of the first two methods.
PhysicalFileProvider PhysicalFileProvider provides access to the physical file system. It encapsulates the System.IO.File type, which scopes to all paths to a directory and its subdirectories. This type of scope restricts access to a directory and its subdirectories, preventing operations outside of scope from accessing the file system. When instantiating such a provider, you must provide it with a directory path that the server can use as the base path for all requests made by this provider (which restricts access requests outside of the path). In a ASP.NET Core application, you can instantiate a PhysicalFileProvider provider directly, or you can request an IFileProvider interface by using constructor dependency injection in the controller and service. The latter results in solutions that are often more flexible and easier to test.
Creating a PhysicalFileProvider is actually very simple, just materialize it and pass it a physical path. You can then traverse the content through its directory or provide subpaths to get information about a specific file.
Modify the ConfigureServices() method of the Startup class to register the services needed to access local files, and then add them to the middleware through constructor injection in the middleware, so that you can control the access path of the files in one place (i.e. when the application starts)
|