Search This Blog

Tuesday, November 27, 2018

SharePoint CSOM Check if Folder Exits


FolderCollection folders = oList.RootFolder.Folders;
                String folderUrl = "/Lists/TestList/" + DateTime.Now.ToString("MMM-yyyy");
                IEnumerable<Folder> existingFolders = clientContext.LoadQuery<Folder>(folders.Where(folder => folder.ServerRelativeUrl == folderUrl));
                clientContext.ExecuteQuery();
                Folder existingFolder = existingFolders.FirstOrDefault();
                if (existingFolder.Name == DateTime.Now.ToString("MMM-yyyy"))
                {
                    //add item inside folder
                    var itemCreateInfo = new SP.ListItemCreationInformation();
                    // need to specify full path after site domain            
                    itemCreateInfo.FolderUrl = siteUrl + "/Lists/TestList/" + DateTime.Now.ToString("MMM-yyyy");
                    ListItem oListItem = oList.AddItem(itemCreateInfo);
                    oListItem["Title"] = Environment.UserName;
                    oListItem["Model"] = model;
                    oListItem["Count"] = count++;
                    oListItem.Update();
                    clientContext.ExecuteQuery();
                }
                else
                {
                    //Enable Folder creation for the list
                    oList.EnableFolderCreation = true;
                    oList.Update();
                    clientContext.ExecuteQuery();
                    //To create the folder
                    ListItemCreationInformation itemFolderCreateInfo = new ListItemCreationInformation();
                    itemFolderCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                    itemFolderCreateInfo.LeafName = DateTime.Now.ToString("MMM-yyyy");
                    ListItem newItem = oList.AddItem(itemFolderCreateInfo);
                    newItem["Title"] = DateTime.Now.ToString("MMM-yyyy");
                    newItem.Update();
                    clientContext.ExecuteQuery();

                    //add item inside folder
                    var itemCreateInfo = new SP.ListItemCreationInformation();
                    // need to specify full path after site domain            
                    itemCreateInfo.FolderUrl = siteUrl + "/Lists/TestList/" + DateTime.Now.ToString("MMM-yyyy");
                    ListItem oListItem = oList.AddItem(itemCreateInfo);
                    oListItem["Title"] = Environment.UserName;
                    oListItem["Model"] = model;
                    oListItem["Count"] = count++;
                    oListItem.Update();
                    clientContext.ExecuteQuery();
                }

No comments:

Post a Comment