I have done app registration in Azure Portal and i have a tenantId, ClientId and clientSecret.
I want to upload file using Microsoft.Graph SDK in C#.
I have to upload file using file path and with the document library name.
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Sites.GetAllSites;
namespace UploadFiles;
public class GraphHandler
{
public GraphServiceClient GraphClient { get; set; }
public GraphHandler(string tenantId, string clientId, string clienSecret)
{
GraphClient = CreateGraphClient(tenantId, clientId, clienSecret);
}
public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
{
var option = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredentials = new ClientSecretCredential(tenantId, clientId, clientSecret, option);
var scope = new[] { "https://graph.microsoft.com/.default" };
return new GraphServiceClient(clientSecretCredentials, scope);
}
}
I want to use this Graph Handler.
How can it be possible?
Create a Microsoft Entra ID application and grant API permissions like below:
To upload the file to SharePoint document library, make use of below code:
using System.Net.Http.Headers;
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
namespace UserProperties
{
public class GraphHandler
{
public GraphServiceClient GraphClient { get; set; }
public GraphHandler()
{
var clientId = "ClientID";
var clientSecret = "ClientSecret";
var tenantId = "TenantID";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var scopes = new[] { "https://graph.microsoft.com/.default" };
GraphClient = new GraphServiceClient(clientSecretCredential, scopes);
}
public async Task UploadFileToSharePoint(string siteId, string driveId, string fileName, string filePath)
{
try
{
var uploadUrl = $"https://graph.microsoft.com/v1.0/sites/{siteId}/drives/{driveId}/items/root:/{fileName}:/content";
byte[] fileBytes = File.ReadAllBytes(filePath);
using (var httpClient = new HttpClient())
{
var accessToken = await GetAccessTokenAsync();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
using (var httpRequest = new HttpRequestMessage(HttpMethod.Put, uploadUrl))
{
httpRequest.Content = new ByteArrayContent(fileBytes);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
using (var response = await httpClient.SendAsync(httpRequest))
{
response.EnsureSuccessStatusCode();
Console.WriteLine("File uploaded successfully.");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error uploading file: {ex.Message}");
}
}
private async Task<string> GetAccessTokenAsync()
{
var clientId = "ClientID";
var clientSecret = "ClientSecret";
var tenantId = "TenantID";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var tokenRequestContext = new TokenRequestContext(new string[] { "https://graph.microsoft.com/.default" });
var accessTokenResult = await clientSecretCredential.GetTokenAsync(tokenRequestContext);
return accessTokenResult.Token;
}
}
class Program
{
static async Task Main(string[] args)
{
var handler = new GraphHandler();
var siteId = "SiteID";
var driveId = "DriveID";
var fileName = "rukk.txt";
var filePath = "C:/Users/rukmini/Downloads/rukk.txt";
await handler.UploadFileToSharePoint(siteId, driveId, fileName, filePath);
}
}
}
File uploaded successfully:
To get the site ID of the site, use the below query:
https://graph.microsoft.com/v1.0/sites?search=testrukk
To get the Drive ID (Document library ID), use the below query:
https://graph.microsoft.com/v1.0/sites/SiteID/drives