Rename a Folder using EPiServer.Web.Hosting.UnifiedDirectory

While reading the EPiServer 5 SDK documentation, i found this:

Rename a Folder

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

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

        int e = -1;
        while (path.IndexOf(oldName, ++e) > -1) ;

        StringBuilder sb = new StringBuilder();
        sb.Append(path.Substring(0, e - 1));
        sb.Append(name);
        sb.Append("/");

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

What a convenient way of renaming a folder 🙂 Good thing that you don’t have to do it too often.

Peter

Leave a Reply

Your email address will not be published. Required fields are marked *