How to upload small files in sharepoint using C# SDK Microsoft.Graph Version="5.4.0"

Kapil Khubchandani 0 Reputation points
2023-04-05T18:43:28.4033333+00:00

Hi Could you please provide a sample code on How to upload small files in sharepoint using C# SDK version Version="5.4.0". The examples I find mostly based on old version of sdks. in the below code I dont seemed to find Request() method on content object.

GraphServiceClient graphClient = new GraphServiceClient( authProvider );
using var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(@"The contents of the file goes here."));
await graphClient.Me.Drive.Items["{driveItem-id}"].Content
	.Request()
	.PutAsync<DriveItem>(stream);

not sure If I am missing additional nuget package. GraphApi

I am anyway have written following code which uploads empty file without any content.


 public async Task<string> UploadNewFile(string driveId, string filePath, IFormFile file, 
            CancellationToken cancellationToken)
        {
            using var mst = new MemoryStream();
            file.CopyTo(mst);

            await _adekGraph.graphServiceClient.Drives[driveId]
                                  .Root
                                  .ItemWithPath(file.FileName)
                                  .Content
                                  .PutAsync(mst, cancellationToken: cancellationToken);
       
            return "file uploaded";

        }

This method is inside a service configured in Program.cs. I am using .net 7. Thanks for the help.

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,858 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,879 questions
{count} votes

1 answer

Sort by: Most helpful
  1. RaytheonXie_MSFT 32,241 Reputation points Microsoft Vendor
    2023-04-06T02:18:18.1133333+00:00

    Hi @Kapil Khubchandani , You can try to make one extra call to get new drive item

    var driveItem = await GraphClient.Drives[driveId].Root.ItemWithPath(filePath).GetAsync();
    
    

    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.

    2 people found this answer helpful.