SharePoint CSOM Check if Folder Exist and Delete It

This method help you to check if a folder exist into a list. Hereby this code check if a folder “shared with everyone” exist into a OneDrive for Business, documents library and then delete it.

///
/// method to delete the default shared with everyone folder in od4b
///
private void deleteSharedWithEveryoneFolder(string userEmail)
{
string email = formatUserEmail(userEmail);
using(ClientContext clientContext = new ClientContext("https://mytenant-my.sharepoint.com/personal/"+email)){
Web web = clientContext.Web;
Web webroot = clientContext.Site.RootWeb;
clientContext.Load(webroot);
clientContext.Load(web);
List list = webroot.GetList("personal/" + email + "/Documents");
clientContext.Load(list);
FolderCollection folders = list.RootFolder.Folders;
clientContext.Load(folders);
IEnumerable<Folder> existingFolders = clientContext.LoadQuery(
folders.Include(
folder => folder.ServerRelativeUrl)
);
clientContext.ExecuteQuery();
string folderUrl = web.ServerRelativeUrl + "/Documents/shared with Everyone";
if(existingFolders.FirstOrDefault(
folder => folder.ServerRelativeUrl.ToLower() == folderUrl.ToLower()) != null)
{
var folderToDelete = web.GetFolderByServerRelativeUrl(folderUrl);
folderToDelete.DeleteObject();
clientContext.ExecuteQuery();
}
}
}

///
/// Method to format the user email address in the MySite URL, following the rule from SP
///
///String, email address to format /// a string of the email address well formated
private string formatUserEmail(string email)
{
// apply the rule to have the user email in the correct format
email = email.Replace("@", "_");
email = email.Replace(".", "_");
return email;
}
Advertisements
This entry was posted in SharePoint. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s