Using Microsoft Graph with C# and ASP.NET to Add a File to OneDrive

One can utilize the Client credentials provider to upload small files (<4M). For larger files, refer to the guide on how to upload them using an upload session. The ASP.NET MVC app provides a comprehensive preview and editing experience for Markdown text files from OneDrive and SharePoint through File Handlers 2.0. Additionally, the Data Robot Azure Function is a sample application that uses an Azure Function to manage webhook notifications and data collaboration in Excel files.

Question:

I am attempting to upload a file to OneDrive that is not currently present. While I was able to modify an existing file, I am having difficulty creating a completely new file. I utilized the

Microsoft.Graph

library for this task.

Below is the functioning code that can be used to modify a file that already exists.

public async Task 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(stream);
            return View("Index");
        }
        catch (ServiceException ex)
        {
            return RedirectToAction("Error", "Home", new { message = "ERROR retrieving messages", debug = ex.Message });
        }
    }


Solution:

Consider utilizing the

ChunkedUploadProvider

tool included in the SDK. Not only is it more user-friendly, but it also enables you to upload files of any size, as opposed to just those under 4MB.

An illustration of the utilization of

ChunkedUploadProvider

can be located within the unit test of

OneDriveUploadLargeFile

.

Uploading files remains consistent for both replacing and creating them. However, it is important to note that when uploading, you must specify the file name instead of solely referencing the existing Item number.

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

Frequently Asked Questions

Posted in Uncategorized