EPiServer: Using the new Unified File System

I hope you find my research on the new EPiServer CMS Unified File System useful. Here are some example code to get you going. The most tricky part is to manually create a page folder if it does not exsist

Getting a handle to an existing file:
UnifiedFile file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath) as UnifiedFile;

Get or Create a Page Folder:

int folderId = (int) page.Property["PageFolderID"].Value;

string pageDirectoryRootVirtualPath = VirtualPathHandler.PageDirectoryRootVirtualPath;
IPageDirectory pageDirectory = HostingEnvironment.VirtualPathProvider.GetDirectory(pageDirectoryRootVirtualPath) as IPageDirectory;
string virtualPathFromFolderId = VirtualPathUtilityEx.Combine(pageDirectoryRootVirtualPath, VirtualPathUtility.AppendTrailingSlash(folderId.ToString()));

UnifiedDirectory directory = HostingEnvironment.VirtualPathProvider.GetDirectory(virtualPathFromFolderId) as UnifiedDirectory;
if (directory == null) {
    directory = pageDirectory. CreateSubdirectory(folderId.ToString(), page);

NOTE! Folder will not “exist” for real until a file is saved inside it. It is important to call CreateSubdirectory with the page as parameter to setup security correctly!

Getting a handle to a new file:

UnifiedFile file = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath) as UnifiedFile;
if (file == null) {
    string virtualDir = VirtualPathUtility.GetDirectory(virtualPath);
    UnifiedDirectory directory = HostingEnvironment.VirtualPathProvider.GetDirectory(virtualDir) as UnifiedDirectory;
    return directory.CreateFile(VirtualPathUtility.GetFileName(virtualPath));
return file;

Example of reading UnifiedFile:
Bitmap image = null;
using (Stream stream = file.Open()) {
image = (Bitmap) Image.FromStream(stream);

Example of writing with UnifiedFile:

using (Stream stream = file.Open(FileMode.Create, FileAccess.Write)) {
image.Save(stream, encoderInfo, encoderParams);