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(""+email)){
Web web = clientContext.Web;
Web webroot = clientContext.Site.RootWeb;
List list = webroot.GetList("personal/" + email + "/Documents");
FolderCollection folders = list.RootFolder.Folders;
IEnumerable<Folder> existingFolders = clientContext.LoadQuery(
folder => folder.ServerRelativeUrl)
string folderUrl = web.ServerRelativeUrl + "/Documents/shared with Everyone";
folder => folder.ServerRelativeUrl.ToLower() == folderUrl.ToLower()) != null)
var folderToDelete = web.GetFolderByServerRelativeUrl(folderUrl);

/// 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;
This entry was posted in SharePoint. Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s