Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete File in SharePoint folder using C#

I am using SharePoint ExcelService to manipulate an excel file and then save it to the Shared Documents folder using

ExcelService.SaveWorkbookCopy()


Now I want to delete those files I saved earlier. What is the best way to achieve this using C# in a Asp.Net MVC Application?

I tried it using the REST Service, but I could not really find any tutorials and as the code is now, I get a WebException "The remote server returned an error: (403) Forbidden." I tried two versions for my REST URL, neither worked.

var fileSavePath = "http://sharepointserver/Collaboration/workrooms/MyWebSiteName/Shared%20Documents/";
var excelRestPath_1 = "http://sharepointserver/Collaboration/workrooms/MyWebSiteName/_api/web/";
var excelRestPath_2 = "http://sharepointserver/_api/web/";

    public static bool DeleteExcelFromSharepoint(int id, string excelRestPath)
    {
        try
        {
            string filePath = "/Shared%20Documents/" + id + ".xlsm";
            string url = excelRestPath + "GetFileByServerRelativeUrl('" + filePath + "')";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "DELETE";
            request.Headers.Add(HttpRequestHeader.IfMatch, "*");
            request.Headers.Add("X-HTTP-Method", "DELETE");

            request.Credentials = System.Net.CredentialCache.DefaultCredentials;

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new ApplicationException(String.Format("DELETE failed. Received HTTP {0}", response.StatusCode));
                }
                return true;
            }

        }
        catch (Exception ex)
        {
            CustomLogger.Error("Error deleting Excel from Sharepoint", ex);
            return false;
        }
    }
like image 528
katho2404 Avatar asked Nov 08 '25 02:11

katho2404


1 Answers

Use nuget package Microsoft.SharePointOnline.CSOM:

using (var sp = new ClientContext("webUrl"))
{
    sp.Credentials =  System.Net.CredentialCache.DefaultCredentials;
    sp.Web.GetFileByServerRelativeUrl(filePath).DeleteObject();
    sp.ExecuteQuery();
}

that will ensure that file is removed - if you want to make sure the file existed during removal:

using (var sp = new ClientContext("webUrl"))
{
    sp.Credentials =  System.Net.CredentialCache.DefaultCredentials;
    var file = sp.Web.GetFileByServerRelativeUrl(filePath);
    sp.Load(file, f => f.Exists);
    file.DeleteObject();
    sp.ExecuteQuery();
    if (!file.Exists)
        throw new System.IO.FileNotFoundException();
}
like image 101
Ryszard Fiński Avatar answered Nov 09 '25 18:11

Ryszard Fiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!