0

am trying to do a simple operation "Delete file from document library using CSOM" As i have only the Relative path http://hostname/subsite/subsite/doclibname/sample.docx

I used below code to get the File object and then delete it.

Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl(relativePath);                    
clientContext.Load(file);
file.DeleteObject();
clientContext.ExecuteQuery();

The code executes without errors. However the file doesn't get deleted.

Googled for it. Getting solutions of using LibraryName. However in real scenario i won't be getting the document library name. I will be just getting URL.

Kindly advise.

6
  • It seems issue of the file path only. What is the full path you are passing in "relativePath" variable ? Try accessing "file.Name" after loading file, to verify that you are able to load the file using URL. Yashesh Nagori Commented Mar 20, 2018 at 9:32
  • Hi Yahesh, Thank you for your reply. I added "ClientContext.ExecuteQuery();" line after Load() and checked for File.Name it is showing File name. The value for "relativePath" is "Departments/IT/testdoclib/sample.docx" Kindly advise Commented Mar 20, 2018 at 10:15
  • Note: If the file does not exist, the Delete method silently fails and does not throw a FileNotFoundException So try and load: .Load(file, f => f.Exists); and check the property after execute Commented Mar 20, 2018 at 11:22
  • Hi Andres, i checked in the document library itself. It is there as it is. Commented Mar 20, 2018 at 11:31
  • No... You are supposed to check in CSOM if you can access the file before deleting it, not the UI Commented Mar 20, 2018 at 12:56

1 Answer 1

1

Please use relative path as: "/subsite/subsite/doclibname/sample.docx".

Microsoft.SharePoint.Client.File file = clientContext.Web.GetFileByServerRelativeUrl("/subsite/subsite/doclibname/sample.docx");

You are passing absolute path and trying to get file using relative one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.