Friday, November 14, 2008

Some useful routines when using SPFolders with SPListItems

Working with SPFolders and SPLists is not as straight forward as it should be. The following methods could help:

/// <summary>

/// Creates a folder (recursively  required). 

/// </summary>

/// <param name="list">The SharePoint list</param>

/// <param name="folderPath">Folder structure: eg: 2008/11/Sales</param>

public static void CreateFolder(SPList list, string folderPath)

{

    if (list == null)

        throw new ApplicationException("List is not specified.");

 

    if (string.IsNullOrEmpty(folderPath))

        throw new ApplicationException("Folder Path is not specified.");

 

    string[] hierarchy = folderPath.Split('/');

    string currentPath = string.Empty;

 

    foreach (string level in hierarchy)

    {

        if (!string.IsNullOrEmpty(currentPath))

            currentPath += "/";

 

        currentPath += level;

 

        if (!DoesFolderExist(list, currentPath))

        {

            SPListItem folder = list.Folders.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);

            folder["Title"] = currentPath;

            folder.Update();

        }

    }

}

 

/// <summary>

/// Returns whether a folder exists within a list.

/// </summary>

/// <param name="list">The SharePoint list</param>

/// <param name="folderPath">Folder structure: eg: 2008/11/Sales</param>

/// <returns></returns>

public static bool DoesFolderExist(SPList list, string folderPath)

{

    if (list == null)

        throw new ApplicationException("List is not specified.");

 

    if (string.IsNullOrEmpty(folderPath))

        throw new ApplicationException("Folder Path is not specified.");

 

    SPFolder folder = GetFolder(list, folderPath);

    return folder.Exists;

}

 

/// <summary>

/// Returns a folder from a list.  If folder does not exist, the Exist property will be FALSE. 

/// </summary>

/// <param name="list">The SharePoint list</param>

/// <param name="folderPath">Folder structure: eg: 2008/11/Sales</param>

/// <returns></returns>

public static SPFolder GetFolder(SPList list, string folderPath)

{

    if (list == null)

        throw new ApplicationException("List is not specified.");

 

    if (string.IsNullOrEmpty(folderPath))

        throw new ApplicationException("Folder Path is not specified.");

 

    return list.ParentWeb.GetFolder(list.RootFolder.Url + "/" + folderPath);

}



To follow on from these examples. Another option is to take advantage of .NET extensions and make these methods extensions of the SPList class (change the method signatures as follows):

public static void CreateFolder(this SPList list, string folderPath)

public static bool DoesFolderExist(this SPList list, string folderPath)

public static SPFolder GetFolder(this SPList list, string folderPath)

No comments: