使用C#删除SharePoint文件夹中的文件

时间:2015-06-26 11:38:16

标签: c# asp.net-mvc rest sharepoint

我使用SharePoint ExcelService来操作excel文件,然后使用

将其保存到Shared Documents文件夹
ExcelService.SaveWorkbookCopy()


现在我想删除我之前保存的那些文件。在Asp.Net MVC应用程序中使用C#实现此目的的最佳方法是什么?

我尝试使用REST服务,但我找不到任何教程,因为代码现在,我得到一个WebException"远程服务器返回错误:(403)Forbidden。" 我为我的REST URL尝试了两个版本,但都没有。

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

3 个答案:

答案 0 :(得分:2)

使用nuget package Microsoft.SharePointOnline.CSOM

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

将确保删除文件 - 如果要确保在删除期间存在该文件:

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

答案 1 :(得分:1)

如果您使用的是REST,则可以参考该链接 (https://msdn.microsoft.com/en-us/library/office/dn450841.aspx#bk_File

我的示例代码是:

string resourceUrl = "https://<BaseURL>/sites/<SubSite>/_api/web/GetFileByServerRelativeUrl('/sites/<SubSite>/Documents/New Folder/xyz.docx')";            

        var wreq = WebRequest.Create(resourceUrl) as HttpWebRequest;
        wreq.Headers.Remove("X-FORMS_BASED_AUTH_ACCEPTED");
        wreq.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    wreq.Headers.Add("X-HTTP-Method", "DELETE");
        //wreq.Headers.Add("Authorization", "Bearer " + AccessToken);
        wreq.UseDefaultCredentials = true;
        wreq.Method = "POST";
        wreq.Accept = "application/json; odata=verbose";
        wreq.Timeout = 1000000;
        wreq.AllowWriteStreamBuffering = true;
        wreq.ContentLength = 0;
        string result = string.Empty;
        string JsonResult = string.Empty;
        try
        {
            WebResponse wresp = wreq.GetResponse();}
        catch (Exception ex)
        {
            LogError(ex);
            result = ex.Message;
        }

答案 2 :(得分:1)

尝试了上面的答案,但仍然没有删除文件,我发现了这个并且它完美无缺

var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(“FullSharePointURIofDocument“);
request.Timeout = System.Threading.Timeout.Infinite;
request.Credentials = new 
System.Net.NetworkCredential(“SharePointUser“,”SharePointUserPassword“);
request.Method = “DELETE“;
var response = (System.Net.HttpWebResponse)request.GetResponse();

感谢BizTalkBox