Download File From SharePoint 365

后端 未结 2 2024
我在风中等你
我在风中等你 2020-12-03 09:01
string remoteUri = \"http://www.contoso.com/library/homepage/images/\";
            string fileName = \"ms-banner.gif\", myStringWebResource = null;
            // C         


        
相关标签:
2条回答
  • 2020-12-03 09:41

    This error occurs since the request is not authenticated. In order to access resource in Office/SharePoint Online you could utilize SharePointOnlineCredentials class from SharePoint Server 2013 Client Components SDK (user credentials flow).

    The following example demonstrates how to download a file from SPO:

    const string username = "username@tenant.onmicrosoft.com";
    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);
         }  
    }
    
    0 讨论(0)
  • 2020-12-03 09:54

    I was facing the same issue and tried the answer suggested by Vadim Gremyachev. However, it still kept giving 403 error. I added two extra headers to force form based authentication like below:

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

    After this it started working. So the full code goes like below:

    const string username = "username@tenant.onmicrosoft.com";
    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 讨论(0)
提交回复
热议问题