Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
654 views
in Technique[技术] by (71.8m points)

c# - Download File From SharePoint 365

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}" .......

", 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("
Downloaded file saved in the following file system folder:
" + Application.StartupPath);

I'am Using this code from MSDN Web Site

But I have coming across the error: 403 forbidden

Can someone Help me Put this working ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = "[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);
     }  
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...