2

我正在尝试使用下载 Office 365 SharePoint 库中存在的项目,WebcClient.DownloadFile()但出现此异常:

例外 :

The remote server returned an error: (403) Forbidden.

示例代码:

NetworkCredential credential = new NetworkCredential("username", "password", "aaa.onmicrosoft.com");
WebClient webClient = new WebClient();
webClient.Credentials = credential;
webClient.DownloadFile(@"https://aaa.sharepoint.com/testDoc/test.pdf", @"c:/test.pdf");
4

3 回答 3

6

另一种选择是利用SharePoint Online Client Components SDK中的 SharePointOnlineCredentials 类

SharePointOnlineCredentials 类表示提供凭据以访问 SharePoint Online 资源的对象

先决条件

SharePoint Online 客户端组件 SDK

如何从 SharePoint Online 下载文件

 public static void DownloadFile(string userName, string password, string fileUrl, string filePath)
 {
        var securePassword = new SecureString();
        foreach (var c in password)
        {
            securePassword.AppendChar(c);
        }
        using (var client = new WebClient())
        {
            client.Credentials = new SharePointOnlineCredentials(userName, securePassword);
            client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
            client.DownloadFile(fileUrl, filePath);
        }
}
于 2014-08-28T11:17:12.453 回答
2

在朋友的帮助下,我设法破解了这个 SharePoint 在线身份验证的东西 :)

我被Wictor Wilén指出了这篇博文的方向。

而我的使用 Wictors 声明库代码的 WebClient 调用......

var claimsHelper = new MsOnlineClaimsHelper(sharepointOnlineUrl, username, password);

var client = new WebClient();
client.Headers[ "Accept" ] = "/";
client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Headers.Add(HttpRequestHeader.Cookie, claimsHelper.CookieContainer.GetCookieHeader(new Uri(sharepointOnlineUrl))  );

var document = client.DownloadString( documentUrl );
于 2012-10-31T12:52:34.623 回答
2

您需要添加一些内容来解决您的问题,称为 Headers 和 UserAgent。

 public static void method()
        {
         //   NetworkCredential myCredentials = new NetworkCredential("username", "password", "aaa.onmicrosoft.com");
            WebClient w = new WebClient();
            var ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            w.Headers["Accept"] = "/";
            w.Headers.Add(HttpRequestHeader.UserAgent, ua);
            w.Credentials = myCredentials;
          w.DownloadFile(url, @"c:/name.doc"); 
        }

它从 Office 365 中的团队站点库为我下载文件。但它给了我一个下载的文件。我剩下的唯一问题:该文件不包含您要下载的真实信息。我正在尝试解决这个问题几天 - 这是我迄今为止得到的最好结果。也许你可以用这些新信息帮助我。请告诉我:)

于 2012-10-03T07:43:32.567 回答