2014-05-15 84 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

偉大的解決方案,我做了:) –