using Azure.Identity; using System.Net.Http.Headers; using Microsoft.Graph; using Microsoft.Identity.Client; using Azure.Core; namespace rgbc_sds.services.Services { public class FileUploadService { public async Task GenerateAccessToken(string tenantId, string clientId, string clientSecret, string[] scopes, string siteId) { // using Azure.Identity; var options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud }; var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options); var accessToken = await clientSecretCredential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes) { }); return accessToken.Token.ToString(); } public async Task GetSharepointSitesAsync(string accessToken) { var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/sites"); request.Headers.Add("Prefer", "apiversion=2.1"); request.Headers.Add("Authorization", "Bearer " + accessToken); var content = new StringContent(string.Empty); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); request.Content = content; var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } public async Task GetSharepointDrives(string accessToken, string siteId) { var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/sites/" + siteId + "/drives"); request.Headers.Add("Authorization", "Bearer " + accessToken); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); string result = response.Content.ReadAsStringAsync().Result; //return await response.Content.ReadAsStringAsync(); return result; } public async Task UploadFile(string accessToken, string siteId, string clientId, string tenantId) { // Define the path of the file to upload string fileName = "UploadedFile.txt"; string filePath = "C:\\Users\\DewaldStander\\OneDrive - Silicon Overdrive\\Documents\\UploadedFile.txt"; // Create an instance of the GraphServiceClient using client credentials authentication var client = await CreateGraphServiceClientAsync(clientId, tenantId, accessToken); // Upload the file to SharePoint await UploadFileToSharePoint(client, siteId, filePath, fileName); return "File uploaded successfully."; } static async Task CreateGraphServiceClientAsync(string clientId, string tenantId, string accessToken) { // Configure the MSAL authentication provider var confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(clientId) .WithTenantId(tenantId) .Build(); // Define the scopes required string[] scopes = new string[] { "https://graph.microsoft.com/.default" }; // Create an AuthenticationProvider with the access token var authenticationProvider = new DelegateAuthenticationProvider((requestMessage) => { requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); return Task.CompletedTask; }); // Create the GraphServiceClient with the AuthenticationProvider var graphClient = new GraphServiceClient(authenticationProvider); return graphClient; } static async Task UploadFileToSharePoint(GraphServiceClient client, string siteId, string filePath, string fileName) { using (Stream stream = new FileStream(filePath, FileMode.Open)) { var uploadSession = client.Sites[siteId].Drive.Root .ItemWithPath(fileName) .CreateUploadSession() .Request() .PostAsync() .Result; // create upload task var maxChunkSize = 320 * 1024; var largeUploadTask = new LargeFileUploadTask(uploadSession, stream, maxChunkSize); // create progress implementation IProgress uploadProgress = new Progress(uploadBytes => { Console.WriteLine($"Uploaded {uploadBytes} bytes of {stream.Length} bytes"); }); // upload file UploadResult uploadResult = largeUploadTask.UploadAsync(uploadProgress).Result; if (uploadResult.UploadSucceeded) { Console.WriteLine("File uploaded to user's OneDrive root folder."); } } } } }