请记住将应用程序权限(客户端凭据流)分配给应用程序注册。见Application permission to Microsoft Graph。
您可以使用Client credentials provider。
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantID)
.WithClientSecret(clientSecret)
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
Upload small file (
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
using var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("The contents of the file goes here."));
await graphClient.Users[{upn or userID}].Drive.Items["{item-id}"].Content
.Request()
.PutAsync<DriveItem>(stream);
如果要上传大文件,请查看Upload large files with an upload session。
更新:
在工具 -> NuGet 包管理器 -> 包管理器控制台中使用Install-Package Microsoft.Graph.Auth -IncludePrerelease。
它同时支持uploading a new file 和replacing an existing item。
获取物品id的方法请参考Get a file or folder。
例如获取/folder1/folder2的item id(在Microsoft Graph Explorer进行快速测试):
GET https://graph.microsoft.com/v1.0/users/{userID}/drive/root:/folder1:/children
它将列出文件夹 1 中的所有子项,包括文件夹 2。然后就可以找到folder2的item id了。
更新 2:
客户端凭据提供者是应用程序身份,而以下所有提供者都是用户身份。
由于您要访问个人 OneDrive(包括用户身份),您可以选择Authorization code provider 或Interactive provider。
授权码提供者:您需要为您的网络应用实现交互式登录并使用此提供者。
交互式提供程序:您可以轻松地使用此提供程序在控制台应用中实现交互式登录。
您可以通过第二家提供商进行快速测试。
请注意,您应该将委派(个人 Microsoft 帐户)权限添加到应用注册中。见Delegated permission to Microsoft Graph。
在这种情况下,您应该将代码中的所有graphClient.Users[{upn or userID}] 修改为graphClient.Me。
恐怕您必须实现登录交互身份验证流程才能访问个人 OneDrive。