Creating Folders programmatically in SharePoint 2013
Asked Answered
P

3

14

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

using (var context = new Microsoft.SharePoint.Client.ClientContext(sharePointSite))
{
    context.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(user, password);

    Web web = context.Web;

    Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle(<upper level folder>);
    docs.EnableFolderCreation = true;

    docs.RootFolder.Folders.Add(folderName);

    context.ExecuteQuery();

    return true;
}

I am having troubles creating sub folders in folders that I have created using this code already. So like if I wanted to create a folder called Feb under Documents this would do that. But if I wanted to create a folder called Week 2 under the new folder Feb. It won't do that. I get this error:

{"List 'Feb' does not exist at site with URL 'https://my.sharepoint.com/sites/labels'."}

I realize that the problem is probably docs.RootFolder.Folders.Add(folderName); because Feb wouldn't be the root folder and when it looks for it an exception would be thrown.

So I was hoping that someone could help me out with some code to add sub folders to already created folders. I am using Visual Stuidos 2010 and can't upgrade to 2012 otherwise I would. I have the 2013 Microsoft.Sharepoint.Client dll's that can be referenced in VS 2010.

Pyridoxine answered 24/2, 2014 at 23:17 Comment(0)
R
32

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");
Romantic answered 25/2, 2014 at 10:8 Comment(3)
Vadim, your solution worked perfectly. I have a follow up though, how would I access a folder like "Share Documents/FolderA". I get an error that says it doesn't exist on the sharepoint site. Because I want to upload a file to the sub folder A and I need to access it.Pyridoxine
Brett, i am glad it helped. The answer has been updated to reflect the case of getting Folder client object. In your comment i guess there is a typo: Share Documents -> Shared DocumentsRomantic
Which SharePoint permissions to check in case of 401, unauthorized error?Feeney
B
3

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");
Blueprint answered 25/2, 2014 at 6:3 Comment(2)
I can't seem to find GetTryGetList.Fisch
That's because the method is called 'TryGetList' and not 'GetTryGetList'. I tried to edit the post but the number of corrected characters is too small.Chari
S
0

To add a folder after a known specific node in the QuickLinks List, try the following:

ClientContext context = new ClientContext("https://companySP.com/sites/RootSite");
NetworkCredential _myCredentials = new NetworkCredential(userName, password);

context.AuthenticationMode = ClientAuthenticationMode.Default;
context.Credentials = _myCredentials;
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Console.WriteLine($"Connected to {context.Web.Title}");
/*  Connection made to Sharepoint Site  */

NavigationNodeCollection ql = context.Web.Navigation.QuickLaunch;
context.Load(ql);
context.ExecuteQuery();
Console.WriteLine("Current nodes:\n");
NavigationNode addAfterNode = null;
foreach (NavigationNode navNode in ql)
{
   Console.WriteLine(navNode.Title + " - " + navNode.Url);
   if (navNode.Title == "Existing List Name In Quicklinks")
   {
      addAfterNode = navNode;
      break;
   }
}
/*  Navigation Node Found to Add After in Quick Links  */

NavigationNodeCreationInformation nnci = new NavigationNodeCreationInformation();
nnci.Title = "New List Title";
nnci.Url = "URL of New List Title";

nnci.PreviousNode = addAfterNode;  // Sets the previous node to add after
ql.Add(nnci);
 
context.Load(ql);
context.ExecuteQuery();

context.Web.Update();
Setose answered 14/5, 2021 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.