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
Sign in to the Azure portal.
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.
Search for and select Azure Active Directory.
Under Manage, select App registrations > New registration.
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.
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 type | Permissions (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 |
Application | Files.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.
Step-4: Get Client Id and Tenant Id
just get it and save it somewhere that will be later used in c# code.
C# Code Setup
Step-1: Need to install the following NuGet pkg
- Azure.Identity
- Microsoft.Graph
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.
Step-4: Finally C# code
Final Output
you will find that our text has been uploaded successfully.
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
Post a Comment