4

I have a SharePoint Online where I can connect through my console application successfully:

private static ClientContext GetUserContext()
{
   var o365SecurePassword = new SecureString();

   foreach (char c in o365Password)
   {
       o365SecurePassword.AppendChar(c);
   }

   var o365Credentials = new SharePointOnlineCredentials(o365Username, o365SecurePassword);

   var o365Context = new ClientContext(o365SiteUrl);
   o365Context.Credentials = o365Credentials;

   return o365Context;
}

But what I need now to do is to go into my SharePoint Document Library named "doc_archive" and check if there exists a folder with name "K20170409-01". If not create a new one.

Failed Attempt

ClientContext context = GetUserContext();

Web web = context.Web;
Web webroot = context.Site.RootWeb;
context.Load(web);
context.Load(webroot);

List list = webroot.GetList("doc_archive");
context.Load(list);

FolderCollection folders = list.RootFolder.Folders;
context.Load(folders);

IEnumerable<Folder> existingFolders = context.LoadQuery(
    folders.Include(
    folder => folder.Name)
);
context.ExecuteQuery();

What is the fastest ways to check and create a folder within a document library in SharePoint Online via CSOM (commandline application)?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
STORM
  • 4,005
  • 11
  • 49
  • 98

2 Answers2

5

If you are happy with using external libraries then the OfficeDevPnP.Core has some great CSOM extensions for SharePoint and SharePoint Online. It's readily available as a NuGet package to add to your projects.

For your requirment there is the EnsureFolderPath extension. This function will check if a folder exists, create it if needed and return the Microsoft.SharePoint.Client.Folder object.

Very easy to use:

var webRelativeUrlToFolder = "/doc_archive/K20170409-01"
var folder = cc.Web.EnsureFolderPath(webRelativeUrlToFolder);
cc.Load(folder);
cc.ExecuteQuery();
groveale
  • 467
  • 3
  • 11
1

I can't vouch for how fast this would be, but it works in the end on 0365. Note that it throws a ServerException if the target already exists.

using (var ctx = new ClientContext(siteUrl))
{

     ctx.Credentials = new SharePointOnlineCredentials(username, securePwd);

     var list = new ListCreationInformation()
     {
         Title = title
         Description = "User Created Document Library",
         TemplateType = asDocumentLibrary ? 101 : 100 // 100 is a custom list.
     };

    ctx.Web.Lists.Add(list);

    ctx.ExecuteQuery();
    success = true;
}

Most CSOM examples are found in Powershell. The process in C# CSOM is actually the same, so next time find a Powershell example when a C# one is not available.

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122