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

Upload new file to onedrive using microsoft graph c# asp.net

正在尝试将不存在的文件上传到 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 });
        }
    }

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

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

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

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