Azu*_*ith 5 c# onedrive microsoft-graph
尝试将文件上传到尚不存在的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 });
}
}
Run Code Online (Sandbox Code Playgroud)
我建议使用ChunkedUploadProvider
SDK 中包含的实用程序。除了更容易使用之外,它还允许您上传任何方面的文件,而不仅限于 4MB 以下的文件。
您可以找到有关如何ChunkedUploadProvider
在OneDriveUploadLargeFile
单元测试中使用的示例。
为了回答您的直接问题,上传对于替换和创建文件的工作方式相同。但是,您需要指定文件名而不仅仅是现有的项目编号:
await graphClient.Me
.Drive
.Root
.ItemWithPath("fileName")
.Content
.Request()
.PutAsync<DriveItem>(stream);
Run Code Online (Sandbox Code Playgroud)