Skip to main content

Microsoft Graph API upload large file to SharePoint

How to Upload a file to SharePoint using Microsoft Graph API - C#/.Net?


To make it easier to upload large files, a number of entities in Microsoft Graph support plus some extra file uploads. Instead of attempting to upload the entire file in a single request, the file is divided into smaller pieces and a single request is used to upload a single slice. To make this process easier, the Microsoft Graph SDKs include a large file upload task that handles the uploading of the slices.


Azur AD Setup:

 you need to complete the following steps to configure the azure ad.

Step - 1: Register an application with the Microsoft identity platform


  1. Sign in to the Azure portal.

  2. If you have access to multiple tenants, use the Directories + subscriptions filter in the top menu to switch to the tenant in which you want to register the application.

  3. Search for and select Azure Active Directory.

  4. Under Manage, select App registrations > New registration.

  5. Enter a Display Name for your application. Users of your application might see the display name when they use the app, for example during sign-in. You can change the display name at any time and multiple app registrations can share the same name. The app registration's automatically generated Application (client) ID, not its display name, uniquely identifies your app within the identity platform.

  6.  see more here https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app

Step 2- Grand required permission to App

One of the following permissions is required to call this API. To learn more, including how to choose permissions, see Permissions.

you must have the below-highlighted permissions granted with Admin Consent 

Permission typePermissions (from least to most privileged)
Delegated (work or school account)Files.ReadWrite, Files.ReadWrite.All, Sites.ReadWrite.All
Delegated (personal Microsoft account)Files.ReadWrite, Files.ReadWrite.All
ApplicationFiles.ReadWrite.All, Sites.ReadWrite.All




Step-3:  Create secrete and save it (make sure to keep it secure)

When receiving tokens at a web addressable location, confidential applications can use credentials to identify themselves to the authentication service (using an HTTPS scheme). We recommend using a certificate (rather than a client secret) as a credential for greater assurance.

Create secrete and save it (make sure to keep it secure)

Step-4:  Get Client Id and Tenant Id

just get it and save it somewhere that will be later used in c# code.

Get Client Id and Tenant Id


C# Code  Setup

Step-1: Need to install the following NuGet pkg

  • Azure.Identity
  • Microsoft.Graph

Need to install the following NuGet pkg

Step-2:  Configuration setup

add the following configuration in the appsettings.json, but replace it with your own values that took in from the azure ad app.

"GraphAPISetting": {
  "ClientId": "d956647c-xxxx-xxxx-843b-56f0c7db967a",
  "ClientSecret": "VVe8Q~6Sk~xxxxxxxxqACB7xzxtZ0NEc2n",
  "TenantId": "33f294fc-00af-423d-XXXX-703cXXXXe3ed" 
}



Step-4: Finally C# code

private ClientCredentialProvider _SetAuthToken()
{

//_config - use microsoft configuration, dependecy injection.

   var _tenantId = _config["GraphAPISetting:TenantId"];
    var _clientId = _config["GraphAPISetting:ClientId"];
    var  _clientSecret = _config["GraphAPISetting:ClientSecret"];
    IConfidentialClientApplication confidentialClientApplication =
ConfidentialClientApplicationBuilder
        .Create(_clientId)
        .WithTenantId(_tenantId)
        .WithClientSecret(_clientSecret)

        .Build();
    return new ClientCredentialProvider(confidentialClientApplication);
}

public async Task<void> Upload()
{
   
    string site = "<YOUR DOMAIN, REPLACE HERE>.sharepoint.com";
    string relativePath = "/sites/<YOUR SITE, REPLACE HERE>";

var   _authProvider = _SetAuthToken();

    GraphServiceClient graphClient = new GraphServiceClient(_authProvider);

    Site s = await graphClient
        .Sites[site]
        .SiteWithPath(relativePath)
        .Request()
        .GetAsync();


    using (var fileStream =
        System
        .IO
        .File
        .OpenRead(
            @"myfile.txt"
        ))
    {
        var uploadSession = await graphClient
            .Sites[s.Id]
            .Drive
            .Root
            .ItemWithPath("sometext-1.txt")
            .CreateUploadSession()
            .Request()
            .PostAsync();

        // Max slice size must be a multiple of 320 KiB
        int maxSliceSize = 320 * 1024;
        var fileUploadTask =
            new LargeFileUploadTask<DriveItem>(uploadSession, fileStream,
maxSliceSize);

        var totalLength = fileStream.Length;
        // Create a callback that is invoked after each slice is uploaded
        IProgress<long> progress = new Progress<long>(prog => { });
        try
        {   // Upload the file
            var uploadResult = await fileUploadTask.UploadAsync(progress);

            //Console.WriteLine(uploadResult.UploadSucceeded ?
            //    $"Upload complete, item ID: {uploadResult.ItemResponse.Id}" :
            //    "Upload failed");
        }
        catch (ServiceException ex)
        {
            //Console.WriteLine($"Error uploading: {ex.ToString()}");
        }
    }
}


Final Output

 you will find that our text has been uploaded successfully.

Final Output


Some useful reference 

https://developer.microsoft.com/en-us/graph/graph-explorer

https://docs.microsoft.com/en-us/graph/api/drive-get?view=graph-rest-1.0&tabs=csharp

Comments

Popular posts from this blog

How to Make a Custom URL Shortener Using C# and .Net Core 3.1

C# and .Net Core 3.1:  Make a Custom URL Shortener Since a Random URL needs to be random and the intent is to generate short URLs that do not span more than 7 - 15 characters, the real thing is to make these short URLs random in real life too and not just a string that is used in the URLs Here is a simple clean approach to develop custom solutions Prerequisite:  Following are used in the demo.  VS CODE/VISUAL STUDIO 2019 or any Create one .Net Core Console Applications Install-Package Microsoft.AspNetCore -Version 2.2.0 Add a class file named ShortLink.cs and put this code: here we are creating two extension methods. public   static   class   ShortLink {      public   static   string   GetUrlChunk ( this   long   key ) =>            WebEncoders . Base64UrlEncode ( BitConverter . GetBytes ( key ));      public   static   long   GetK...

Azure key vault with .net framework 4.8

Azure Key Vault  With .Net Framework 4.8 I was asked to migrate asp.net MVC 5 web application to Azure and I were looking for the key vault integrations and access all the secrete out from there. Azure Key Vault Config Builder Configuration builders for ASP.NET  are new in .NET Framework >=4.7.1 and .NET Core >=2.0 and allow for pulling settings from one or many sources. Config builders support a number of different sources like user secrets, environment variables and Azure Key Vault and also you can create your own config builder, to pull in configuration from your own configuration management system. Here I am going to demo Key Vault integrations with Asp.net MVC(download .net framework 4.8). You will find that it's magical, without code, changes how your app can read secretes from the key vault. Just you have to do the few configurations in your web config file. Prerequisite: Following resource are required to run/complete this demo · ...

AWS FREE ASP.NET CORE (.NET 6.0) HOSTING WITH FREE SSL

  FREE ASP.NET CORE (.NET 6.0) Hosting on AWS (Amazon Web Services) Today I was able to host my asp.net 6.0  + ANGULAR 14 application  on AWS Free  Initial Setup of your AWS Account and your Computer Get ready with your asp.net core 3.1 /.net 6 application Install  "AWS toolkit for visual studio 2022" as  visual studio extensions :  it will be required to deploy smoothly from Visual Studio 2022 itself, your life will be easy. Let's finish the AWS account setup  Get signed up with: its free but it will be required a valid credit card or debit card, they will charge nothing for the free services for 1 year * https://portal.aws.amazon.com/billing/signup#/start/email AWS console  for services and offering http://console.aws.amazon.com/ Create a user in AWS Console:  IAM With the help of AWS Identity and Access Management (IAM), you can control who or what has access to the services and resources offered by AWS, centrally manage fine-grained...