Creating Folders programmatically in SharePoint 2013

前端 未结 2 415
无人共我
无人共我 2021-02-05 16:04

Currently I have code that creates a Folder in the Documents directory when run:

using (var context = new Microsoft.SharePoint.Client.ClientContext(         


        
相关标签:
2条回答
  • 2021-02-05 16:55

    You can create Folders like this:

    Microsoft.SharePoint.Client.List docs = web.Lists.TryGetList("upper level folder");
    FolderCollection folderColl = docs.RootFolder.SubFolders;
    Folder newFolder = folderColl.Add("upper level folder/Feb/Week 2");
    
    0 讨论(0)
  • 2021-02-05 16:57

    How to create Folder (including nested) via CSOM in SharePoint 2010/2013

    /// <summary>
    /// Create Folder client object
    /// </summary>
    /// <param name="web"></param>
    /// <param name="listTitle"></param>
    /// <param name="fullFolderUrl"></param>
    /// <returns></returns>
    public static Folder CreateFolder(Web web, string listTitle, string fullFolderUrl)
    {
        if (string.IsNullOrEmpty(fullFolderUrl))
            throw new ArgumentNullException("fullFolderUrl");
        var list = web.Lists.GetByTitle(listTitle);
        return CreateFolderInternal(web, list.RootFolder, fullFolderUrl);
    }
    
    private static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderUrl)
    {
        var folderUrls = fullFolderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
        string folderUrl = folderUrls[0];
        var curFolder = parentFolder.Folders.Add(folderUrl);
        web.Context.Load(curFolder);
        web.Context.ExecuteQuery();
    
        if (folderUrls.Length > 1)
        {
            var subFolderUrl = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
            return CreateFolderInternal(web, curFolder, subFolderUrl);
        }
        return curFolder;
    }
    

    Usage

     using (var ctx = new ClientContext("https://contoso.onmicrosoft.com/"))
     {
           ctx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials("username", "password");
           var folder = CreateFolder(ctx.Web, "Shared Documents", "FolderA/SubFolderA/SubSubFolderA");
     }
    

    How to get Folder client object

    public static Folder GetFolder(Web web, string fullFolderUrl)
    {
        if (string.IsNullOrEmpty(fullFolderUrl))
            throw new ArgumentNullException("fullFolderUrl");
    
        if (!web.IsPropertyAvailable("ServerRelativeUrl"))
        {
            web.Context.Load(web,w => w.ServerRelativeUrl);
            web.Context.ExecuteQuery();
        }
        var folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + fullFolderUrl);
        web.Context.Load(folder);
        web.Context.ExecuteQuery();
        return folder;
    }
    

    Usage

    var existingFolder = GetFolder(ctx.Web, "Shared Documents/FolderA/SubFolderA/SubSubFolderA");
    
    0 讨论(0)
提交回复
热议问题