gpt4 book ai didi

c# - 使用 Microsoft Graph c# asp.net 将新文件上传到 onedrive

转载 作者:太空狗 更新时间:2023-10-30 01:13:31 30 4
gpt4 key购买 nike

尝试将一个不存在的文件上传到 onedrive。我设法让它更新现有文件。但似乎无法弄清楚如何创建一个全新的文件。我使用 Microsoft.Graph 库完成了这项工作。

这是更新现有文件的代码:

public async Task<ActionResult> OneDriveUpload()
{
string token = await GetAccessToken();
if (string.IsNullOrEmpty(token))
{
// If there's no token in the session, redirect to Home
return Redirect("/");
}

GraphServiceClient client = new GraphServiceClient(
new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);

return Task.FromResult(0);
}));


try
{
string path = @"C:/Users/user/Desktop/testUpload.xlsx";
byte[] data = System.IO.File.ReadAllBytes(path);
Stream stream = new MemoryStream(data);
// Line that updates the existing file
await client.Me.Drive.Items["55BBAC51A4E4017D!104"].Content.Request().PutAsync<DriveItem>(stream);

return View("Index");
}
catch (ServiceException ex)
{
return RedirectToAction("Error", "Home", new { message = "ERROR retrieving messages", debug = ex.Message });
}
}

最佳答案

我建议使用 ChunkedUploadProvider SDK 中包含的实用程序。除了更容易使用之外,它还允许您上传任何方面的文件,而不是限于 4MB 以下的文件。

您可以在 OneDriveUploadLargeFile 中找到有关如何使用 ChunkedUploadProvider 的示例单元测试。

要回答您的直接问题,上传对于替换和创建文件的工作方式相同。但是,您确实需要指定文件名而不仅仅是现有的项目编号:

await graphClient.Me
.Drive
.Root
.ItemWithPath("fileName")
.Content
.Request()
.PutAsync<DriveItem>(stream);

关于c# - 使用 Microsoft Graph c# asp.net 将新文件上传到 onedrive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49822779/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com