This is an update to a post I wrote on deleting list items from document libraries, prompted by a comment made on that post asking how to delete Folder(s) from within a document library.
Initially I replied by suggesting the use of the SharePoint object mode, as shown below;
SPWeb web = new SPSite("your site's url").OpenWeb();
web.Folders[“document library name”].SubFolders.Delete(“folder name”);
However, the commenter indicated that he could not use the object model as the code would be executed on a remote client machine, which left the SharePoint Webservices.
I’d not previously attempted to delete folders using CAML before, and as it turns out the CAML is exactly the same as if we were deleting list items, see the post on deleting items from document libraries, but the CAML for deleting a folder named
Folder2 in some document library is shown below;
<Batch PreCalc='TRUE' OnError='Continue'> <Method ID='1' Cmd='Delete'> <Field Name='ID'>2</Field> <Field Name='FileRef'>http://pccal01/mortality/Test/Folder2</Field> </Method> </Batch>
I’ve shown the CAML above with spaces and such for display purposes, your CAML should not contain white space or CR characters. In the second example shown below, the folder name contains a space,
"Folder 1", in this case the
FileRef parameter should not be URL encoded, or contain
_x0020_ replacements etc.
<Batch PreCalc='TRUE' OnError='Continue'> <Method ID='1' Cmd='Delete'> <Field Name='ID'>1</Field> <Field Name='FileRef'>http://pccal01/mortality/Test/Folder 1</Field> </Method> </Batch>
Note: The ID parameter is required to be present in the CAML query, but it is ignored by the webservice, you can safely just set its value to “1”.