通过c#代码在sharepoint中创建嵌套文件夹

时间:2014-04-11 07:00:24

标签: c# sharepoint sharepoint-2010 sharepoint-2013 sharepoint-deployment

如何通过c#代码在sharepoint中创建嵌套文件夹? 例如,我有像“共享文档/文件夹1 /文件夹2 /文件夹3”这样的字符串,我想通过c#代码创建文件夹或跳过文件夹已存在的文件夹。任何建议或代码都是高度评价的。

1 个答案:

答案 0 :(得分:2)

如何使用SharePoint SSOM创建嵌套文件夹

internal static class SPFolderExtensions
{
    /// <summary>
    /// Ensure SPFolder
    /// </summary>
    /// <param name="web"></param>
    /// <param name="listTitle"></param>
    /// <param name="folderUrl"></param>
    /// <returns></returns>
    public static SPFolder CreateFolder(this SPWeb web, string listTitle, string folderUrl)
    {
        if (string.IsNullOrEmpty(folderUrl))
            throw new ArgumentNullException("folderUrl");
        var list = web.Lists.TryGetList(listTitle);
        return CreateFolderInternal(list, list.RootFolder, folderUrl);
    }


    private static SPFolder CreateFolderInternal(SPList list, SPFolder parentFolder, string folderUrl)
    {
        var folderNames = folderUrl.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
        var folderName = folderNames[0];

        var curFolder =
            parentFolder.SubFolders.Cast<SPFolder>()
                        .FirstOrDefault(
                            f =>
                            System.String.Compare(f.Name, folderName, System.StringComparison.OrdinalIgnoreCase) ==
                            0);
        if (curFolder == null)
        {
            var folderItem = list.Items.Add(parentFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder,
                                            folderName);
            folderItem.SystemUpdate();
            curFolder = folderItem.Folder;
        }


        if (folderNames.Length > 1)
        {
            var subFolderUrl = string.Join("/", folderNames, 1, folderNames.Length - 1);
            return CreateFolderInternal(list, curFolder, subFolderUrl);
        }
        return curFolder;
    }
}

关键点:

  • 能够创建嵌套文件夹
  • 现有文件夹不会受到影响

用法

以下示例演示如何在Documents库下创建以下文件夹结构:

Orders
   |
   Orders A
      |
      Orders A1

示例:

var folder = web.CreateFolder("Documents", "Orders/Orders A/Orders A1");