从 SharePoint 365 下载文件

问题描述 投票:0回答:2

我正在使用来自 MSDN 网站的代码:

string remoteUri = "http://www.contoso.com/library/homepage/images/";
string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n\n", fileName, myStringWebResource);
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource,fileName);     
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, myStringWebResource);
Console.WriteLine("\nDownloaded file saved in the following file system folder:\n\t" + Application.StartupPath);

但是我遇到了错误:403禁止

有人可以帮我让它工作吗?

c# sharepoint office365
2个回答
10
投票

我面临着同样的问题,并尝试了 Vadim Gremyachev 建议的答案。但还是一直报403错误。我添加了两个额外的标头来强制基于表单的身份验证,如下所示:

client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");

此后它开始工作。所以完整的代码如下:

const string username = "[email protected]";
const string password = "password";
const string url = "https://tenant.sharepoint.com/";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);

DownloadFile(url,credentials,"/Shared Documents/Report.xslx");


private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
     using(var client = new WebClient())
     {
        client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        client.Headers.Add("User-Agent: Other");
        client.Credentials = credentials;
        client.DownloadFile(webUrl, fileRelativeUrl);
     }  
}

8
投票

出现此错误是因为请求未经过身份验证。为了访问 Office/SharePoint Online 中的资源,您可以利用 SharePoint Server 2013 客户端组件 SDK 中的SharePointOnlineCredentials 类用户凭据流程)。

以下示例演示如何从 SPO 下载文件:

const string username = "[email protected]";
const string password = "password";
const string url = "https://tenant.sharepoint.com/";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);

DownloadFile(url,credentials,"/Shared Documents/Report.xslx");


private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
{
     using(var client = new WebClient())
     {
        client.Credentials = credentials;
        client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
        client.DownloadFile(webUrl, fileRelativeUrl);
     }  
}
© www.soinside.com 2019 - 2024. All rights reserved.