c# - 使用 WebClient 从 SharePoint Online 下载文件

标签 c# sharepoint office365 sharepoint-online

我正在使用 .net 4.8 WebClient 和 Microsoft.SharePointOnline.CSOM 包,尝试从 SharePoint 在线下载文件。

const string username = "myusername@domain.com";
const string password = "mypassword";
const string url = "https://tenant.sharepoint.com/:b:/r/filepath.pdf";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray())
{
    securedPassword.AppendChar(c);
}
var credentials = new SharePointOnlineCredentials(username, securedPassword);
using (var client = new WebClient())
{
    client.Credentials = credentials;
    client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    client.DownloadFile(url, "C:\\temp\\test.pdf"); //this file path definitely exists
}

我收到的错误是 401 未经授权。 我使用相同的凭据注销并登录到 SharePoint 环境,以确保它们是正确的。

我尝试在 header 中添加几个不同的用户代理,看看是否有帮助。

client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
//or
client.Headers.Add("User-Agent: Other");

但这并没有什么不同。

这类似于 Download File From SharePoint 365它使用的代码看起来和我一样,但是Download Document from SharePoint Online using c# webclient stopped working表明发生了一些变化,这种形式的身份验证不再适用于连接到 SharePoint Online。但是,我一直找不到关于我们现在应该使用什么的任何最新文档。

最佳答案

可以引用官方文档提供的代码。
https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest
在我测试时,它运行良好。

public static void DownloadFileViaRestAPI(string webUrl, ICredentials credentials, string documentLibName, string fileName, string path)
        {
            webUrl = webUrl.EndsWith("/") ? webUrl.Substring(0, webUrl.Length - 1) : webUrl;
            string webRelativeUrl = null;
            if (webUrl.Split('/').Length > 3)
            {
                webRelativeUrl = "/" + webUrl.Split(new char[] { '/' }, 4)[3];
            }
            else
            {
                webRelativeUrl = "";
            }

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                client.Credentials = credentials;
                Uri endpointUri = new Uri(webUrl + "/_api/web/GetFileByServerRelativeUrl('" + webRelativeUrl + "/" + documentLibName + "/" + fileName + "')/$value");

                byte[] data = client.DownloadData(endpointUri);
                FileStream outputStream = new FileStream(path + fileName, FileMode.OpenOrCreate | FileMode.Append, FileAccess.Write, FileShare.None);
                outputStream.Write(data, 0, data.Length);
                outputStream.Flush(true);
                outputStream.Close();
            }
        }

        static void Main(string[] args)
        {
            string siteURL = "https://contoso.sharepoint.com/sites/dev";

            //set credential of SharePoint online
            SecureString secureString = new SecureString();
            foreach (char c in "password".ToCharArray())
            {
                secureString.AppendChar(c);
            }
            ICredentials credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials("amos@contoso.onmicrosoft.com", secureString);

            //set credential of SharePoint 2013(On-Premises)
            //string userName = "Administrator";
            //string password = "xxxxxxx";
            //string domain = "CONTOSO";
            //ICredentials credentials = new NetworkCredential(userName, password, domain);

            DownloadFileViaRestAPI(siteURL, credentials, "lib", "test.css", "c:\\SPFX\\");

            Console.WriteLine("success");
            Console.ReadLine();
        }

关于c# - 使用 WebClient 从 SharePoint Online 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64247545/

相关文章:

c# - Android 单声道中的内存高效位图处理

c# - WPF ComboBox 在不应该更改的时候更改

c# - 如何在没有包装器的情况下访问 Skype API?

PowerShell集-MSolUserLicense

c# - 从 Linux 服务器与 C# 桌面应用程序通信的选项?

c# - 何时在 DbContext 构造函数中提供 DbContextOptions 与 OnConfiguring?

SharePoint 2010 - RichImageField 未在显示模式下显示

SharePoint 文档或项目下载/查看事件处理程序?

azure - 通过 Azure Active Directory 进行 Windows 表单例份验证

c# - O365 使用Mailkit 删除邮件?