简体   繁体   中英

How can i download an excel file from sharepoint server?

I have a project (c# console application), in which I want to automatically download an excel file, via URL, with login credentials.

I have been using a webclient to download the file automatically, and all I receive is an html page as response, informing me to login into the site (I have run it in Chrome.)

     private static string url = "[the whole url link to the file, deleted for privacy]";
     public void test()
    {
        const string username = "[mail]";
        const string password = "[password]";

        var securedPassword = new SecureString();
        foreach (var c in password.ToCharArray())
        {
            securedPassword.AppendChar(c);
        }

        var credentials = new SharePointOnlineCredentials(username, securedPassword);

        DownloadFile(url, credentials, @"C:\Documents\ExcelFilesSinc\test.xlsx");
    }


    private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl)
    {
        using (var client = new WebClient())
        {
            client.Credentials = credentials;

            string _UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            client.Headers.Add(HttpRequestHeader.UserAgent, _UserAgent);
            client.DownloadFile(webUrl, fileRelativeUrl);
        }
    }

In this way, the file is generated, but the whole content saved in it is an HTML page that requires me to login to Microsoft. Any suggestions?

You can try to add headers for base auth like

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

see also here: Download File From SharePoint 365

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM