0

I have the followoing code to create a folder inside a document library:-

    ListItemCreationInformation listItemCreationInformation2 = new ListItemCreationInformation();

    // Below are options.
    // (1) File - This will create a file in the list or document library
    // (2) Folder - This will create a foder in list(if folder creation is enabled) or documnt library
    listItemCreationInformation2.UnderlyingObjectType = FileSystemObjectType.Folder;

    // This will et the internal name/path of the file/folder
    listItemCreationInformation2.LeafName = listItem["Title"].ToString() + i["Level1"].ToString();

           try
               {
                 ListItem listItem2 = templatelsit.AddItem(listItemCreationInformation2);
               }
           catch { }

currently i am wrapping the code to add the folder inside a try/catch, so is there a way to check if the folder exists before trying to add it?

1

Try below piece of code:

private static bool FolderExists(ClientContext context, string url)
{
    var folder = context.Web.GetFolderByServerRelativeUrl(url);
    context.Load(folder, f => f.Exists);
    try
    {
        context.ExecuteQuery();

        if (folder.Exists)
        {
            return true;
        }
        return false;
    }
    catch (ServerUnauthorizedAccessException uae)
    {
        Console.WriteLine("You are not allowed to access this folder");
        throw;
    }
    catch (Exception ex)
    {
        Console.WriteLine("Could not find folder.");
        return false;
    }
}

Note: It only load folder.Exists property.

Source: CSOM: Check if Files or Folders exist.

|improve this answer|||||
  • Have you tried this? Is this answer helped you? – Ganesh Sanap Feb 18 at 15:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.