vendredi 26 juin 2015

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;
        }
    }

Aucun commentaire:

Enregistrer un commentaire