CSOM delete items by id range
Get items
public ListItemCollection GetItems(string listRelativUrl, string where, string orderBy, string viewFields, int rowlimit = 100)
{
string xmlView = "";
try
{
List lst = CurrentWeb.GetList(CurrentWeb.ServerRelativeUrl + listRelativUrl);
StringBuilder vf = new StringBuilder();
if (!string.IsNullOrEmpty(viewFields))
{
vf.Append("<ViewFields>");
foreach (string fieldName in viewFields.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
{
vf.Append($"<FieldRef Name='{fieldName.Trim()}' />");
}
vf.Append("</ViewFields>");
}
CamlQuery camlQuery = new CamlQuery();
camlQuery = new CamlQuery();
Logger.LogInfo($"listRelativUrl {listRelativUrl} : <View><Query>{where}{orderBy}</Query>{vf.ToString()}<RowLimit>{rowlimit}</RowLimit></View>");
xmlView = $"<View><Query>{where}{orderBy}</Query>{vf.ToString()}<RowLimit>{rowlimit}</RowLimit></View>";
camlQuery.ViewXml = xmlView;
ListItemCollection coll = lst.GetItems(camlQuery);
SPContext.Load(coll);
SPContext.ExecuteQuery();
Logger.Log($"coll.Count : '{coll.Count}' : camlQuery.ViewXml {camlQuery.ViewXml}");
return coll;
}
catch (ServerException ex1)
{
Logger.LogError($"Error ServerException Common.Sharepoint.SPTools.GetItems url '{_url}' login : '{_login}' " +
$" listRelativUrl '{listRelativUrl}' where '{where}' orderBy '{orderBy}' rowlimit '{rowlimit}' xmlView : '{xmlView}' Exception '{ex1}'");
throw;
}
catch (Exception ex)
{
Logger.LogError($"Error .Common.Sharepoint.SPTools.GetItems url '{_url}' login : '{_login}' " +
$" listRelativUrl '{listRelativUrl}' where '{where}' orderBy '{orderBy}' rowlimit '{rowlimit}' xmlView : '{xmlView}' Exception '{ex}'");
throw;
}
}
delete items
public int DeleteItemByIdRange(string listRelativeUrl, int rowLimit, int from, int to = -1)
{
int deleted = 0;
try
{
string req = "";
if (to == -1)
req = $"<Where><Geq><FieldRef Name='ID'/><Value Type='Counter'>{from}</Value></Geq></Where>";
else
{
if (from > to)
throw new Exception($"DeleteItemByIdRange from should be < than to listRelativeUrl '{listRelativeUrl}' from '{from}' to '{to}'");
req = $"<Where><And><Geq><FieldRef Name='ID' /><Value Type='Counter'>{from}</Value></Geq><Leq><FieldRef Name='ID' /><Value Type='Counter'>{to}</Value></Leq></And></Where>";
}
ListItemCollection coll = GetItems(listRelativeUrl, req, "", "ID", rowLimit);
while (coll.Count > 0)
{
string id = coll[0].Id.ToString();
coll[0].DeleteObject();
this.ExecuteQuery($"DeleteItemByIdRange listRelativeUrl '{listRelativeUrl}' from '{from}' to '{to}' Id = '{id}'");
deleted++;
}
return deleted;
}
catch (Exception ex)
{
Logger.LogError($"Error Sharepoint.SPTools.DeleteItemByIdRange from id '{from}' to id '{to}' url '{_url}' login : '{_login}' Exception '{ex}'");
throw;
}
}
catch ServerException to get more details on CSOM exceptions