Share via

How to upload a file to a Sharepoint DriveItem/folder using C#.

Patrick Cowden 20 Reputation points
Jan 29, 2024, 6:59 PM

This page of documentation https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=http does not include an "Upload" example in C#. I found another support thread in which someone from MS Support offered this method: await graphClient!.Drives[<Drive Id>].Items[<Drive-Item Id>].ItemWithPath(filename).Content.PutAsync(file); I can successfully use that method to upload a file to the correct Sharepoint folder/Drive-Item, but the file uploads with zero bytes. Is that a legitimate C# method to upload a CSV to a Sharepoint folder/Drive-Item? Is there a better method? Thank You, Patrick Cowden (EverService - Enterprise Applications)

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,854 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
11,109 questions
0 comments No comments
{count} votes

Accepted answer
  1. RaytheonXie_MSFT 38,111 Reputation points Microsoft Vendor
    Jan 30, 2024, 2:33 AM

    Hi @Patrick Cowden, You could try to use LargeFileUploadclass that comes as part of the Microsoft Graph C# SDK.

    using var fileStream = File.OpenRead(filePath);
    
    // Use properties to specify the conflict behavior
    // using DriveUpload = Microsoft.Graph.Drives.Item.Items.Item.CreateUploadSession;
    var uploadSessionRequestBody = new DriveUpload.CreateUploadSessionPostRequestBody
    {
        Item = new DriveItemUploadableProperties
        {
            AdditionalData = new Dictionary<string, object>
            {
                { "@microsoft.graph.conflictBehavior", "replace" },
            },
        },
    };
    
    // Create the upload session
    // itemPath does not need to be a path to an existing item
    var myDrive = await graphClient.Me.Drive.GetAsync();
    var uploadSession = await graphClient.Drives[myDrive?.Id]
        .Items["root"]
        .ItemWithPath(itemPath)
        .CreateUploadSession
        .PostAsync(uploadSessionRequestBody);
    
    // Max slice size must be a multiple of 320 KiB
    int maxSliceSize = 320 * 1024;
    var fileUploadTask = new LargeFileUploadTask<DriveItem>(
        uploadSession, fileStream, maxSliceSize, graphClient.RequestAdapter);
    
    var totalLength = fileStream.Length;
    // Create a callback that is invoked after each slice is uploaded
    IProgress<long> progress = new Progress<long>(prog =>
    {
        Console.WriteLine($"Uploaded {prog} bytes of {totalLength} bytes");
    });
    
    try
    {
        // Upload the file
        var uploadResult = await fileUploadTask.UploadAsync(progress);
    
        Console.WriteLine(uploadResult.UploadSucceeded ?
            $"Upload complete, item ID: {uploadResult.ItemResponse.Id}" :
            "Upload failed");
    }
    catch (ODataError ex)
    {
        Console.WriteLine($"Error uploading: {ex.Error?.Message}");
    }
    
    
    

    Please refer to the following document https://learn.microsoft.com/en-us/graph/sdks/large-file-upload?context=graph%2Fapi%2F1.0&view=graph-rest-1.0&tabs=csharp

    ---If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.