Upload new file to onedrive using microsoft graph c# asp.net(使用 microsoft graph c# asp.net 将新文件上传到 onedrive)
问题描述
尝试将文件上传到尚不存在的 onedrive.我设法让它更新现有文件.但似乎无法弄清楚如何创建一个全新的文件.我已经使用 Microsoft.Graph 库完成了这项工作.
Trying to upload a file to onedrive that does not already exist. I have managed to get it to update an existing file. But can't seem to figure out how to create a brand new file. I have done this useing the Microsoft.Graph
library.
以下是用于更新现有文件的代码:
Here is the code that works to update an existing file:
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
实用程序.除了更容易使用之外,它还允许您上传任何方面的文件,而不是仅限于 4MB 以下的文件.
I'd suggest using the ChunkedUploadProvider
utility that is included in the SDK. Aside from being a little easier to work with, it will allow you to upload files of any side rather than being limited to files under 4MB.
您可以在 ChunkedUploadProvider 的示例.Graph.Test/Requests/Functional/OneDriveTests.cs#L39" rel="noreferrer">OneDriveUploadLargeFile
单元测试.
You can find a sample of how to use ChunkedUploadProvider
in the OneDriveUploadLargeFile
unit test.
要回答您的直接问题,上传对于替换和创建文件的工作方式相同.但是,您确实需要指定文件名,而不仅仅是现有的项目编号:
To answer your direct question, uploading works the same for both replacing and creating files. You do however need to specify the file name rather than just an existing Item number:
await graphClient.Me
.Drive
.Root
.ItemWithPath("fileName")
.Content
.Request()
.PutAsync<DriveItem>(stream);
这篇关于使用 microsoft graph c# asp.net 将新文件上传到 onedrive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 microsoft graph c# asp.net 将新文件上传到 onedrive


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04