asp.net mvc - Delete File in SharePoint folder using C# -


i using sharepoint excelservice manipulate excel file , save shared documents folder using

excelservice.saveworkbookcopy() 


want delete files saved earlier. best way achieve using c# in asp.net mvc application?

i tried using rest service, not find tutorials , code now, webexception "the remote server returned error: (403) forbidden." tried 2 versions 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 sharepoint", ex);             return false;         }     } 

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 ensure file removed - if want make sure 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(); } 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -