使用 SaveBinaryDirect (C#) 将文件上传到 SharePoint Online 时出现 401 错误

401 Error When Uploading File to SharePoint Online with SaveBinaryDirect (C#)

我正在开发一个工具,用于将文件从本地驱动器上传到 SharePoint online。

当我尝试通过 SharePoint.Client.File.SaveBinaryDirect() 上传文件时,出现 401:未授权错误

这是我的代码:

var uploadFilePath = @"C:\TestFiles\testFile.pdf";
var uploadFileRelativePath = "/sites/my-site/MyLibrary/testFile.pdf";

using (var ctx = new AuthenticationManager().GetAppOnlyAuthenticatedContext(site,
                    ConfigurationManager.AppSettings["ClientId"], ConfigurationManager.AppSettings["ClientSecret"]))
{
    using (var fileStream = new FileStream(uploadFilePath, FileMode.Open))
    {
        File.SaveBinaryDirect(ctx, uploadFileRelativePath, fileStream, true);
    }
}

事实是,如果我将 SaveBinaryDirect 替换为以下代码,它就可以正常工作:

FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(uploadFilePath);
newFile.Url = "testFile.pdf";
List docs = ctx.Web.Lists.GetByTitle("MyLibrary");
docs.RootFolder.Files.Add(newFile);
ctx.ExecuteQuery();

所以我的工具明确授权上传文件。它只是不适用于 SaveBinaryDirect。

我还是想用SharePoint.Client.File.SaveBinaryDirect上传文件。它的代码更少,我不必手动获取列表和文件夹。

你知道我为什么会收到 401 错误吗?

您不能将仅限应用程序的令牌与 SaveBinaryDirect 方法一起使用:https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/upload-large-files-sample-app-for-sharepoint :

Only use this method if you're using a user-only authentication policy. A user-only authentication policy isn't available in a SharePoint Add-in, but can be used in native device add-ins, Windows PowerShell, and Windows console applications.