Umbraco CMS
CloudHeartcoreDXPMarketplace
13.latest (LTS)
13.latest (LTS)
  • Umbraco CMS Documentation
  • Legacy Documentation
    • Umbraco 11 Documentation
    • Umbraco 8 Documentation
    • Umbraco 7 Documentation
  • Release Notes
  • Contribute
  • Sustainability Best Practices
  • Fundamentals
    • Get to know Umbraco
    • Setup
      • Requirements
      • Installation
        • Install using .NET CLI
        • Install using Visual Studio
        • Local IIS With Umbraco
        • Install using Visual Studio Code
        • Installing Nightly Builds
        • Running Umbraco on Linux/macOS
        • Unattended Installs
      • Upgrade your project
        • Version Specific Upgrades
          • Upgrade from Umbraco 8 to the latest version
          • Migrate content to Umbraco 8
          • Minor upgrades for Umbraco 8
          • Upgrade to Umbraco 7
          • Minor upgrades for Umbraco 7
      • Server setup
        • Running Umbraco On Azure Web Apps
        • Hosting Umbraco in IIS
        • File And Folder Permissions
        • Runtime Modes
        • Umbraco in Load Balanced Environments
          • Load Balancing Azure Web Apps
          • Standalone File System
          • Advanced Techniques With Flexible Load Balancing
          • Logging With Load Balancing
    • Backoffice
      • Sections
      • Property Editors
        • Built-in Property Editors
          • Checkbox List
          • Color Picker
          • Content Picker
          • DateTime
          • Date
          • Decimal
          • Email Address
          • Eye Dropper Color Picker
          • File Upload
          • Image Cropper
          • Label
          • List View
          • Markdown Editor
          • Media Picker
          • Media Picker (Legacy)
          • Member Group Picker
          • Member Picker
          • Multi Url Picker
          • Multinode Treepicker
          • Repeatable Textstrings
          • Numeric
          • Radiobutton List
          • Slider
          • Tags
          • Textarea
          • Textbox
          • Toggle
          • User Picker
          • Block Editors
            • Block Grid
            • Block List
            • Build a Custom View for a Block
            • Configuring Block Editor Label Properties
          • Dropdown
          • Grid Layout (Legacy)
            • What Are Grid Layouts?
            • Configuring The Grid Layout
            • Settings And Styling
            • Grid Editors
            • Build Your Own Editor
            • Rendering Grid In a Template
            • Grid Layout Best Practices
            • Add Values Programmatically
          • Rich Text Editor
            • Rich Text Editor Configuration
            • Rich Text Editor Styles
            • Rich Text Editor Plugins
            • Blocks in Rich Text Editor
      • Login
      • Content Templates
      • Infinite Editing
      • Log Viewer
      • Language Variants
      • Settings Dashboards
    • Data
      • Defining Content
        • Default Document Types
        • Document Type Localization
      • Creating Media
        • Default Data/Media Types
      • Members
      • Data Types
        • Default Data Types
      • Scheduled Publishing
      • Using Tabs
      • Users
      • Relations
      • Dictionary Items
      • Content Version Cleanup
    • Design
      • Templates
        • Basic Razor Syntax
        • Named Sections
        • Razor Cheatsheet
      • Rendering Content
      • Rendering Media
      • Partial Views
      • Partial View Macro Files
      • Stylesheets And JavaScript
    • Code
      • Service APIs
      • Subscribing To Notifications
      • Creating Forms
      • Debugging
        • Logging
      • Source Control
  • Implementation
    • Learn how Umbraco works
    • Routing
      • Controller & Action Selection
      • Execute Request
      • Request Pipeline
    • Custom Routing
      • Adding a hub with SignalR and Umbraco
    • Controllers
    • Data Persistence (CRUD)
    • Composing
    • Integration Testing
    • Nullable Reference Types
    • Services and Helpers
      • Circular Dependencies
    • Unit Testing
  • Extending
    • Customize the editing experience
    • Dashboards
    • Sections & Trees
      • Sections
      • Trees
        • Tree Actions
      • Searchable Trees (ISearchableTree)
    • Property Editors
      • Property Value Converters
      • Property Actions
      • Tracking References
      • Declaring your property editor
      • Content Picker Value Converter Example
    • Package Manifest
    • Macro Parameter Editors
    • Health Check
      • Health Check Guides
        • Click-Jacking Protection
        • Content/MIME Sniffing Protection
        • Cross-site scripting Protection (X-XSS-Protection header)
        • Debug Compilation Mode
        • Excessive Headers
        • Fixed Application Url
        • Folder & File Permissions
        • HTTPS Configuration
        • Macro Errors
        • Notification Email Settings
        • SMTP
        • Strict-Transport-Security Header
    • Language Files & Localization
    • Backoffice Search
    • Backoffice Tours
    • Backoffice UI API Documentation
    • Content Apps
    • Creating a Custom Database Table
    • Embedded Media Providers
    • Custom File Systems (IFileSystem)
      • Using Azure Blob Storage for Media and ImageSharp Cache
    • Configuring Azure Key Vault
    • Packages
      • Creating a Package
      • Language file for packages
      • Listing a Package on the Umbraco Marketplace
      • Good practice and defaults
      • Packages on Umbraco Cloud
      • Installing and Uninstalling Packages
      • Maintaining packages
      • Create accessible Umbraco packages
      • Example Package Repository
    • UI Library
  • Reference
    • Dive into the code
    • Configuration
      • Basic Authentication Settings
      • Connection strings settings
      • Content Dashboard Settings
      • Content Settings
      • Data Types Settings
      • Debug settings
      • Examine settings
      • Exception filter settings
      • FileSystemProviders Configuration
      • Global Settings
      • Health checks
      • Hosting settings
      • Imaging settings
      • Indexing settings
      • Install Default Data Settings
      • Keep alive settings
      • Logging settings
      • Maximum Upload Size Settings
      • Models builder settings
      • NuCache Settings
      • Package Migration
      • Plugins settings
      • Request handler settings
      • Rich text editor settings
      • Runtime minification settings
      • Runtime settings
      • Security Settings
      • Serilog settings
      • Tours settings
      • Type finder settings
      • Unattended
      • Web routing
    • Templating
      • Macros
        • Managing macros
        • Partial View Macros
      • Models Builder
        • Introduction
        • Configuration
        • Builder Modes
        • Understand and Extend
        • Using Interfaces
        • Tips and Tricks
      • Working with MVC
        • Working with MVC Views in Umbraco
        • View/Razor Examples
        • Using MVC Partial Views in Umbraco
        • Using View Components in Umbraco
        • Querying & Traversal
        • Creating Forms
    • Querying & Models
      • IMemberManager
      • IPublishedContentQuery
      • ITagQuery
      • UDI Identifiers
      • UmbracoContext helper
      • UmbracoHelper
      • IPublishedContent
        • IPublishedContent Collections
        • IPublishedContent IsHelpers
        • IPublishedContent Property Access & Extension Methods
    • Routing & Controllers
      • Routing requirements for backoffice authentication
      • Custom MVC controllers (Umbraco Route Hijacking)
      • Custom MVC Routes
      • Custom Middleware
      • URL Rewrites in Umbraco
      • Special Property Type aliases for routing
      • URL Redirect Management
      • Routing in Umbraco
        • FindPublishedContentAndTemplate()
        • IContentFinder
        • Inbound request pipeline
        • Outbound request pipeline
        • Published Content Request Preparation
      • Surface controllers
        • Surface controller actions
      • Umbraco API Controllers
        • Umbraco Api - Authorization
        • Umbraco Api - Routing & Urls
    • Content Delivery API
      • Custom property editors support
      • Extension API for querying
      • Media Delivery API
      • Protected content in the Delivery API
      • Output caching
      • Property expansion and limiting
      • Additional preview environments support
    • Webhooks
      • Expanding Webhook Events
    • API versioning and OpenAPI
    • Searching
      • Examine
        • Examine Management
        • Examine Manager
        • Custom indexing
        • PDF indexes and multisearchers
        • Quick-start
    • Using Notifications
      • Notification Handler
      • CacheRefresher Notifications Example
      • ContentService Notifications Example
      • Creating And Publishing Notifications
      • Determining if an entity is new
      • MediaService Notifications Example
      • MemberService Notifications Example
      • Sending Allowed Children Notification
      • Umbraco Application Lifetime Notifications
      • EditorModel Notifications
        • Customizing the "Links" box
      • Hot vs. cold restarts
    • Inversion of Control / Dependency injection
    • Management
      • Models Reference
        • Content
        • ContentType
        • DataType
        • DictionaryItem
        • Language
        • Media
        • MediaType
        • Relation
        • RelationType
        • ServerRegistration
        • Template
      • Services Reference
        • AuditService
        • ConsentService
        • DataTypeService
        • DomainService
        • EntityService
        • ExternalLoginService
        • FileService
        • MacroService
        • MediaService
        • MemberGroupService
        • MemberService
        • MemberTypeService
        • NotificationService
        • PackagingService
        • PublicAccessService
        • RedirectUrlService
        • RelationService
        • ServerRegistrationService
        • TagService
        • TextService
        • ContentService
          • Create content programmatically
          • Publish content programmatically
        • ContentTypeService
          • Retrieving content types
          • Retrieving content types
        • LocalizationService
          • Retrieving languages
        • UserService
          • Creating a user
    • Plugins
      • Creating Resolvers
      • Finding types
    • Cache & Distributed Cache
      • Accessing the cache
      • ICacheRefresher
      • IServerMessenger
      • Getting/Adding/Updating/Inserting Into Cache
      • Examples
        • Working with caching
    • Response Caching
    • Security
      • API rate limiting
      • BackOfficeUserManager and Events
      • Cookies
      • Replacing the basic username/password check
      • External login providers
      • Locking of Users and password reset
      • Reset admin password
      • Umbraco Security Hardening
      • Umbraco Security Settings
      • Sensitive data
      • Sanitizing the Rich Text Editor
      • Setup Umbraco for a FIPS Compliant Server
      • HTTPS
      • Two-factor Authentication
      • Server-side file validation
    • Scheduling
    • Common Pitfalls & Anti-Patterns
    • API Documentation
    • Debugging with SourceLink
    • Language Variation
    • UmbracoMapper
    • Distributed Locks
    • AngularJS
      • Directives
        • umbLayoutSelector
        • umbLoadIndicator
        • umbProperty
      • Services
        • Editor Service
        • Events Service
          • changeTitle
  • Tutorials
    • Overview
    • Creating a Basic Website
      • Getting Started
      • Document Types
      • Creating Your First Template
      • CSS and Images
      • Displaying the Document Type Properties
      • Creating a Master Template
      • Creating Pages and Using the Master Template
      • Setting the Navigation Menu
      • Articles and Article Items
      • Adding Language Variants
      • Conclusions
    • Creating a Custom Dashboard
      • Extending the Dashboard using the Umbraco UI library
    • Creating a Property Editor
      • Adding configuration to a property editor
      • Integrating services with a property editor
      • Adding server-side data to a property editor
    • Creating a Multilingual Site
    • Add Google Authentication (Users)
    • Add Microsoft Entra ID authentication (Members)
    • Creating a Backoffice Tour
    • Creating Custom Database Tables with Entity Framework
    • The Starter Kit
      • Lessons
        • Customize the Starter Kit
        • Add a Blog Post Publication Date
          • Add a Blog Post Publication Date
          • Add a Blog Post Publication Date
        • Add Open Graph
          • Add Open Graph - Step 1
          • Add Open Graph - Step 2
          • Add Open Graph - Step 3
          • Add Open Graph - Step 4
          • Add Open Graph - Summary
        • Ask For Help and Join the Community
    • Editor's Manual
      • Getting Started
        • Logging In and Out
        • Umbraco Interface
        • Creating, Saving and Publishing Content Options
        • Finding Content
        • Editing Existing Content
        • Sorting Pages
        • Moving a Page
        • Copying a Page
        • Deleting and Restoring Pages
      • Working with Rich Text Editor
      • Version Management
        • Comparing Versions
        • Rollback to a Previous Version
      • Media Management
        • Working with Folders
        • Working with Media Types
        • Cropping Images
      • Tips & Tricks
        • Refreshing the Tree View
        • Audit Trail
        • Notifications
        • Preview Pane Responsive View
        • Session Timeout
    • Multisite Setup
    • Member Registration and Login
    • Custom Views for Block List
    • Connecting Umbraco Forms and Zapier
    • Creating an XML Sitemap
    • Implementing Custom Error Pages
Powered by GitBook
On this page
  • Media Filesystem
  • Creating a custom file system
  • Accessing the media file system from code
  • MediaPath Scheme
  • Other IFileSystems
  • Stylesheet Filesystem
  • Custom providers
Edit on GitHub
Export as PDF
  1. Extending

Custom File Systems (IFileSystem)

A guide to creating custom file systems in Umbraco

PreviousEmbedded Media ProvidersNextUsing Azure Blob Storage for Media and ImageSharp Cache

Last updated 2 months ago

Media Filesystem

Before considering a custom media file system, be sure to first read about the configuration options for UmbracoMediaPath and UmbracoMediaPhysicalRootPath in the . These configurations may save you from creating your own media file system entirely.

By default, Umbraco uses an instance of PhysicalFileSystem to handle the storage location of the media archive (wwwroot/media).

This can be configured by composition:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Infrastructure.DependencyInjection;

namespace UmbracoExamples.Composition;

public class SetMediaFileSystemComposer : IComposer
{
    public void Compose(IUmbracoBuilder builder)
    {
        builder.SetMediaFileSystem((factory) =>
        {
            IHostingEnvironment hostingEnvironment = factory.GetRequiredService<IHostingEnvironment>();
            var folderLocation = "~/CustomMediaFolder";
            var rootPath = hostingEnvironment.MapPathWebRoot(folderLocation);
            var rootUrl = hostingEnvironment.ToAbsolute(folderLocation);

            return new PhysicalFileSystem(
                factory.GetRequiredService<IIOHelper>(),
                hostingEnvironment,
                factory.GetRequiredService<ILogger<PhysicalFileSystem>>(),
                rootPath,
                rootUrl);
        });
    }
}

When creating a PhysicalFileSystem it takes some dependencies like IIOHelper, but the last two parameters are what we're interested in.

The rootPath is where your media will be stored on the disk. Since netcore by default stores files in the wwwroot, we must put our desired folder somewhere within wwwroot to ensure that we use hostingEnvironment.MapPathWebRoot(~/CustomMediaFolder). The ~ will be mapped to your wwwroot folder, so the final rootPath will be your/project/path/wwwroot/CustomMediaFolder. The ~ is therefore important.

The rootUrl is the base URL that your media files will be served from. In this case, your image URL could look something like mysite.com/CustomMediaFolder/MyAwesomePicture.png. Again the ~ is important.

In the code sample above, the rootUrl must map to the the same physical location as rootPath, which again must be placed under wwwroot. If you want to store the media files outside of wwwroot there is an extra step involved; you need to instruct netcore to include static files from a different physical location.

The rootUrl is the base URL that your media files will be served from. In this case, your image URL could look something like mysite.com/CustomMediaFolder/MyAwesomePicture.png. Again the ~ is important. With the code sample above, the rootUrl must map to the same physical location as rootPath, otherwise, you will get 404's for your images.

If you want to store the media files outside of wwwroot there is an extra step involved; you need to instruct netcore to include static files from a different physical location.

In the Program.cs file, register a new static file location like so:

...
WebApplication app = builder.Build();

app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(Path.Combine("C:", "storage", "umbracoMedia")),
        RequestPath = "/CustomPath"
    });

The PhysicalFileProvider takes a single parameter, the RootPath. This is the rooted filesystem path using directory separator chars and not ending with a directory separator, eg: c:\storage\umbracoMedia or \\server\path. The safest way to achieve this is using Path.Combine.

You also have to specify the RequestPath. This is the relative URL where the media will be served using URL separator chars and not ending with a separator, eg: /CustomPath or /Media.

Now you can use your newly registered static file location as if it was wwwroot. Notice how you no longer need to use hostingEnvironment.MapPathWebRoot(folderLocation), since you're no longer trying to map the location to somewhere within wwwroot, but instead use your newly registered static file location.

public void Compose(IUmbracoBuilder builder)
{
    builder.SetMediaFileSystem((factory) =>
    {
        IHostingEnvironment hostingEnvironment = factory.GetRequiredService<IHostingEnvironment>();
        var rootPath = Path.Combine("C:", "storage", "umbracoMedia");
        var rootUrl = hostingEnvironment.ToAbsolute("/CustomPath");

        return new PhysicalFileSystem(
            factory.GetRequiredService<IIOHelper>(),
            hostingEnvironment,
            factory.GetRequiredService<ILogger<PhysicalFileSystem>>(),
            rootPath,
            rootUrl);
    });
}

This is almost the same as when registering a location within the wwwroot folder. The only difference is that rootPath is now set to the path we gave the PhysicalFileProvider and the rootUrl is the same as we set as the RequestPath in the StaticFileOption.

Our media is now stored in C:\storage\umbracoMedia, and is served from the base URL /CustomPath, so an image URL will look something like mysite.com/CustomPath/MyAwesomePicture.png.

Creating a custom file system

You can replace PhysicalFileSystem with a custom file system implementation - eg. if you want your media files stored on Amazon S3 or elsewhere outside your site.

To achieve this, you must first create your own file system by implementing the interfaces IFileSystem and IFileProviderFactory (the interfaces that are implemented by PhysicalFileSystem).

You then replace the media filesystem by composition using IUmbracoBuilder.SetMediaFileSystem(...) (as is demonstrated in the paragraphs above), but instead of returning a PhysicalFileSystem, you return your own file system implementation.

Accessing the media file system from code

The example below uses UmbracoAuthorizedApiController which has been removed from Umbraco 14. Use ManagementApiControllerBase class instead.

Since the default media file system can be swapped with custom implementations, you should never access the implementation directly. Umbraco uses a manager class called MediaFileManager. You can get a reference to this manager class via dependency injection in the constructor for your custom class or controller:

public class ImagesController : UmbracoAuthorizedApiController
{
    private readonly MediaFileManager _mediaFileManager;

    public ImagesController(MediaFileManager mediaFileManager)
    {
        _mediaFileManager = mediaFileManager;
    }

{...}

You can then access the configured file system provider through _mediaFileManager.FileSystem, which is the same way Umbraco will access the file system provider.

MediaPath Scheme

The MediaPath Scheme defines the current set of rules that decide the format of the Media Path when it is saved into the media archive wherever it is located.

By default the MediaPath scheme used by Umbraco is the UniqueMediaPathScheme this generates a unique 'folder' to place the uploaded image in eg.

/media/dozdrg2f/mylovelyimage.jpg

/media is defined by the PhysicalFileSystem and 'dozdrg2f' is generated by the UniqueMediaPathScheme.

You can create your own logic for the path by implementing IMediaPathScheme and setting it during composition with:

builder.Services.AddUnique<IMediaPathScheme, MyCustomMediaPathScheme>();

OriginalMediaPathScheme is deprecated as of Umbraco 9. If you are migrating from earlier versions, we recommend using IMediaPathScheme to implement your own logic.

Other IFileSystems

Umbraco also registers instances of PhysicalFileSystem for the following parts of Umbraco that persist to 'files':

  • MacroPartialsFileSystem

  • PartialViewsFileSystem

  • StylesheetsFileSystem

  • ScriptsFileSystem

  • MvcViewsFileSystem

These are accessible via dependency injection.

public class FileSystemLocations
{
    private readonly FileSystems _fileSystems;
    public FileSystemLocations(FileSystems fileSystems)
    {
        _fileSystems = fileSystems;
        var macroPartialsFileSystem = _fileSystems.MacroPartialsFileSystem;
    }

IFileSystem, MediaFileManager, and FileSystems are located in the Umbraco.Cms.Core.IO namespace.

Stylesheet Filesystem

Like with the media file system it is also possible to replace the stylesheet filesystem with your own implementation of IFileSystem in a composer. It's important to note here that, unlike media file system, you cannot replace the filesystem with a PhysicalFileSystem using a different root path or root URL, this will not work, and will cause issues since the root path is coupled to the virtual path, given by the frontend, e.g. /css/MyBeautifulStyle.css.

When replacing the stylesheet filesystem, you don't need to register it, since it's only available through Filesystems, what you need to do instead is configure the FileSystems to use your implementation for the StylesheetsFileSystem.

The IUmbracoBuilder has an extension method for configuring the FileSystems, you need to invoke this method with an action that accepts an IServiceProvider and the FileSystems you will configure, configuring the FileSystems can look like this:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Infrastructure.DependencyInjection;

namespace UmbracoExamples.Composition;

public class FileSystemComposer : IComposer
{
    public void Compose(IUmbracoBuilder builder)
    {
        builder.ConfigureFileSystems((factory, systems) =>
        {
            IIOHelper ioHelper = factory.GetRequiredService<IIOHelper>();
            IHostingEnvironment hostingEnvironment = factory.GetRequiredService<IHostingEnvironment>();
            ILogger<PhysicalFileSystem> logger = factory.GetRequiredService<ILogger<PhysicalFileSystem>>();
            GlobalSettings settings = factory.GetRequiredService<IOptions<GlobalSettings>>().Value;

            var path = settings.UmbracoCssPath;
            var rootPath = hostingEnvironment.MapPathWebRoot(path);
            var rootUrl = hostingEnvironment.ToAbsolute(path);
            var fileSystem = new YourFileSystemImplementaion(ioHelper, hostingEnvironment, logger, rootPath, rootUrl);

            systems.SetStylesheetFilesystem(fileSystem);
        });
    }
}

Where YourFileSystemImplementation is a class that implements IFileSystem. This should always be done in a composer, since we do not recommend trying to change filesystems on the fly.

After the SetStylesheetFileSystem method has run, FileSystems.StylesheetsFileSystem will return the instance that was created in the ConfigureFileSystems extension method.

Custom providers

There is an Azure Blob Storage provider:

For inspiration on building a custom file system, have a look at the .

configuration reference docs
Azure Blob Storage file system implementation
Azure Blob Storage