2014-05-15 87 views
2
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); 

我'使用从MSDN Web Site下载文件从SharePoint 365

但我已经越过错误来验证码:403禁止

有人可以帮我把这个工作?

+0

为什么验证类型是您要下载的文件?你有没有尝试设置'myWebClient.Credentials =新的NetworkCredential(“用户”,“通过”);'基本身份验证? – Nate

+0

尝试凭证后发生同样的错误! – Nevesito

回答

5

因为该请求未经过身份验证,则会出现此错误。为了在Ofice365/SharePoint Online中执行身份验证,您可以使用SharePoint Server 2013 Client Components SDK中的SharePointOnlineCredentials class

下面的例子演示了如何从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.DownloadFile(webUrl, fileRelativeUrl); 
    } 
} 
+0

我在上面的代码中得到了403异常。还注意到fileRelativeUrl应该是文件将要保存的本地系统的路径。 –

+0

这是否适用于ADFS支持sp在线? –

3

我面临同样的问题,并试图通过瓦迪姆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); 
    } 
} 
+0

伟大的解决方案,我做了:) –