November Happy Hour will be moved to Thursday December 5th.

Loading...
Area: Optimizely CMS

Recommended reading 

Note: This topic has no later version.

Table of Contents

Introduction

This document describes how to programatically access files and folders in EPiServer CMS. You will learn how to create, rename, move, copy and delete files and folders, and how to get versions of a specific file in the EPiServer CMS File manager. For more information on how to use the File Manager, refer to the EPiServer CMS User Documentation.

Check List

  • Check that the user has the correct access permissions before attempting any actions on files and folders.
  • Check that paths given as arguments are correct.
  • Check that a path to a file actually points to a file.
  • Check that a path to a folder actually points to a folder.

Sometimes in the following samples the code will refer to a method named IsFolder. This is a user-defined method that looks as follows:

C#
protected bool IsFolder(string path)
{
    return HostingEnvironment.VirtualPathProvider.DirectoryExists(path);
}

Creating a Folder

To access files and folders in EPiServer CMS, make sure you are referencing the EPiServer.Web.Hosting DLL in your source code.

To create a folder using the UnifiedDirectory class, use the following code:

C#
protected void CreateFolder(string path, string name)
{
    UnifiedDirectory.CreateDirectory(path + name);
}

Renaming a Folder

There is no Rename method on the UnifiedDirectory class. To rename a folder you need to call the MoveTo method as follows:

C#
public void RenameFolder(string path, string oldName, string name)
{
    if (IsFolder(path))
    {
        UnifiedDirectory directory = System.Web.Hosting.HostingEnvironment.
            VirtualPathProvider.GetDirectory(path + oldName) as UnifiedDirectory;

        StringBuilder sb = new StringBuilder();
        sb.Append(path);
        sb.Append(name);
        sb.Append("/");

        directory.MoveTo(sb.ToString());
    }
}

Deleting a Folder

To delete a folder using the UnifiedDirectory class, use the following code:

C#
protected void DeleteFolder(string path)
{
    if (IsFolder(path))
    {
        UnifiedDirectory directory = 
        System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetDirectory(path) as UnifiedDirectory;
        directory.Delete();
    }
}

Uploading a File

To upload a file you need to:

  1. Create a UnifiedDirectory instance of the directory where you want to create the file.
  2. Get an instance of the contents of the file in the shape of a Stream.
  3. Call EPiServer.Web.Hosting.UnifiedDirectory.CreateFile(string) on the UnifiedDirectory instance with FileMode set to CreateNew to create a new Stream.
  4. Copy the contents of the received Stream to the Stream you have created.
  5. Close all Streams.
C#
protected void UploadFile(Stream fileContent, string fileName, string destinationPath)
{
    UnifiedDirectory dir = System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetDirectory(destinationPath)
        as UnifiedDirectory;
    UnifiedFile uFile = dir.CreateFile(fileName);
    Stream s = uFile.Open(FileMode.CreateNew);

    byte[] buffer = new byte[fileContent.Length];
    int numBytesToRead = (int)fileContent.Length;

    fileContent.Read(buffer, 0, numBytesToRead);

    s.Write(buffer, 0, buffer.Length);
    s.Close();

    fileContent.Close();
}

Renaming, Moving and Copying a File

There is no Rename method on the EPiServer.Web.Hosting.UnifiedFile class. To rename a file you need to call the MoveTo method.
See the following samples on how to rename, copy, move or delete a file:

C#
protected void UnifiedFileMethods(string path)
{
    // If the root folder of the site is EPiServerCMS5, the path string could for 
    // example be "/EPiServerCMS5/Documents/mypicture.jpg"

    // Create a UnifiedFile instance from the supplied path
    UnifiedFile file =
        System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(path)
        as UnifiedFile;

    // To create a copy of the file in the same directory:
    file.CopyTo("/Documents/MyCopy.jpg");

    // To Move the file to another directory (if you wish to rename a file, 
    // simply "move" the file to the current folder but with a new name):
    file.MoveTo("/Documents/AnotherFolder/FileName.jpg");

    // To delete the file:
    file.Delete();
}

Getting Versions of a File

To retrieve an IList containing the versions of a file, try the following code:

C#
public IList<UnifiedVersion> GetFileVersions(string path)
{
    return (System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(path) as VersioningFile).GetVersions();
}

Best Practice

Before handling a file or folder, check that you have the correct type. A file object can for instance be either a VersioningFile or a UnifiedFile. The GetVersions function should be completed to look as follows to better handle possible errors. Also remember that what a user might or might not do with a file or folder depends on access permissions. Always check what roles the current user is in and that the user has the correct permissions to execute the method requested.

A good recommendation when dealing with site paths is to use the System.Uri class for parsing schemes and paths. This way you eliminate the sometimes risky business of parsing strings manually when building a URL.

See the following improved version of the GetVersions method on how to check that we have a valid path pointing to a Versioning File.

Always check that the supplied path actually points to a folder and not a file if the requested method expects a folder (and vice versa). See the IsFolder sample at the beginning of this guide.

C#
// Getting file versions, and making sure we have a versioning file
public IList<UnifiedVersion> GetFileVersions_Safe(string path)
{
    VirtualFile file = System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(path);
    // Could not resolve the path into a file at all
    if (file == null)
    {
        throw new ArgumentException("Given path is not a valid file path");
    }
    VersioningFile versioningFile = file as VersioningFile;
    // We have a file, check that the path points to a versioning file and not a native file
    if (versioningFile == null)
        throw new ArgumentException("Given path is not a versioning file");
    return versioningFile.GetVersions();
}
Do you find this information helpful? Please log in to provide feedback.

Last updated: Mar 25, 2013

Recommended reading