I have custom Database, this Database having SharePoint Item URL like(http://yoursite.com/Shared Documents/a.pdf), so my challenge to remove this file from sharepoint Library using Client Object Model.
3 Answers
ClientContext clientContext = new ClientContext("http://sharepoint:6666");
Uri uri = new Uri(filePath);
List spList = clientContext.Web.Lists.GetByTitle("Shared Documents");
Microsoft.SharePoint.Client.CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
query.ViewXml = "<View>"
+ "<Query>"
+ "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>" + filename + "</Value></Eq></Where>"
+ "</Query>"
+ "</View>";
// execute the query
ListItemCollection listItems = spList.GetItems(query);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (ListItem listitem in listItems)
{
listitem.DeleteObject();
clientContext.ExecuteQuery();
}
FileLeafRef is internal column name of Name.
yes you can try below rest call
url: http://site url/_api/web/GetFileByServerRelativeUrl('/Shared Documents/a.pdf')
method: POST
headers:
Authorization: "Bearer " + accessToken
X-RequestDigest: form digest value
IF-MATCH: etag or "*"
X-HTTP-Method:"DELETE"
Hope this will work for you :)
Added on a little to the answer. It works perfectly. Suggest passing the Main Site name int he sLoginUri and then the Folder Location as not everyone has a "Shared Documents".
#region Delete a File
//============================================================================== Delete a File from a Library
public static bool DeleteAFile(string sFileName, string sFldrLoc, string sUserName, string sPassword,
string sLoginUri, ref String sError)
{
bool bRetVal = false;
string sourceFolderName = "/" + sFldrLoc;
string documentRelativePath = sLoginUri + sourceFolderName + "/" + sFileName;
try
{
SP.ClientContext clientContext = new SP.ClientContext(sLoginUri);
//NetworkCredential credential = System.Net.CredentialCache.DefaultNetworkCredentials;
//clientContext.Credentials = credential;
NetworkCredential credential = new NetworkCredential(sUserName, sPassword, "citgo");
clientContext.Credentials = credential;
Uri uri = new Uri(documentRelativePath);
SP.List spList = clientContext.Web.Lists.GetByTitle(sFldrLoc);
Microsoft.SharePoint.Client.CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
query.ViewXml = "<View>"
+ "<Query>"
+ "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>" + sFileName + "</Value></Eq></Where>"
+ "</Query>"
+ "</View>";
// execute the query
SP.ListItemCollection listItems = spList.GetItems(query);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (SP.ListItem listitem in listItems)
{
listitem.DeleteObject();
clientContext.ExecuteQuery();
bRetVal = true;
}
}
catch (Exception exc)
{
//Log Error Here
sError = exc.Message;
}
return bRetVal;
}
#endregion