Created
December 21, 2016 20:39
-
-
Save andyhuey/de2bde00e398e8925a3770e9950c8f48 to your computer and use it in GitHub Desktop.
CSOM code to delete all items from a SharePoint list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void deleteAllFromList(ClientContext cc, List myList) | |
{ | |
int queryLimit = 4000; | |
int batchLimit = 100; | |
bool moreItems = true; | |
string viewXml = string.Format(@" | |
<View> | |
<Query><Where></Where></Query> | |
<ViewFields> | |
<FieldRef Name='ID' /> | |
</ViewFields> | |
<RowLimit>{0}</RowLimit> | |
</View>", queryLimit); | |
var camlQuery = new CamlQuery(); | |
camlQuery.ViewXml = viewXml; | |
while (moreItems) | |
{ | |
ListItemCollection listItems = myList.GetItems(camlQuery); // CamlQuery.CreateAllItemsQuery()); | |
cc.Load(listItems, | |
eachItem => eachItem.Include( | |
item => item, | |
item => item["ID"])); | |
cc.ExecuteQuery(); | |
var totalListItems = listItems.Count; | |
if (totalListItems > 0) | |
{ | |
Console.WriteLine("Deleting {0} items from {1}...", totalListItems, myList.Title); | |
for (var i = totalListItems - 1; i > -1; i--) | |
{ | |
listItems[i].DeleteObject(); | |
if (i % batchLimit == 0) | |
cc.ExecuteQuery(); | |
} | |
cc.ExecuteQuery(); | |
} | |
else | |
{ | |
moreItems = false; | |
} | |
} | |
Console.WriteLine("Deletion complete."); | |
} |
Saved my day!
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks you @andyhuey