How to Upload Large Files to SharePoint Using Microsoft Graph SDK in C# (Step-by-Step)
Uploading large files to SharePoint can be tricky, but Microsoft Graph SDK’s upload sessions make it reliable by splitting files into manageable chunks. Here’s how to do it in C#—no jargon, just clear steps!
What is an Upload Session?
An upload session lets you:
Upload large files (e.g., >4MB) in smaller chunks.
Resume uploads if the connection drops.
Avoid timeouts common with single-request uploads.
Step 1: Set Up Prerequisites
Install NuGet Packages:
Install-Package Microsoft.Graph Install-Package Microsoft.Graph.Core
Azure App Registration:
Register your app in Azure AD.
Grant Sites.ReadWrite.All (Application permissions).
Step 2: Authenticate with Microsoft Graph
Use the ClientSecretCredential
to authenticate your app:
using Microsoft.Graph; using Azure.Identity; var tenantId = "YOUR_TENANT_ID"; var clientId = "YOUR_CLIENT_ID"; var clientSecret = "YOUR_CLIENT_SECRET"; var credential = new ClientSecretCredential(tenantId, clientId, clientSecret); var graphClient = new GraphServiceClient(credential);
Step 3: Create the Upload Session
Specify the SharePoint file path (replace placeholders):
var siteId = "your-site-id"; // SharePoint site ID var driveId = "your-drive-id"; // Document library ID var fileName = "largefile.zip"; // File name var folderPath = "Shared%20Documents"; // URL-encoded folder path // Request upload session var uploadSession = await graphClient.Sites[siteId] .Drives[driveId] .Root .ItemWithPath($"{folderPath}/{fileName}") .CreateUploadSession() .Request() .PostAsync();
Step 4: Upload the File in Chunks
Use LargeFileUploadTask
to handle chunking automatically:
using var fileStream = File.OpenRead("C:/path/to/largefile.zip"); // Max chunk size (default: 320 KB) var maxChunkSize = 320 * 1024; var uploadTask = new LargeFileUploadTask<DriveItem>( uploadSession, fileStream, maxChunkSize ); // Upload all chunks var uploadResult = await uploadTask.UploadAsync(); if (uploadResult.UploadSucceeded) { Console.WriteLine("File uploaded!"); }
Key Details Explained
Site/Drive IDs:
Find them in SharePoint URL:
https://contoso.sharepoint.com/sites/{site-id}/_layouts/15/...
Use the Graph API to list sites/drives if unsure.
Chunk Size:
Smaller chunks = more requests but better reliability.
Max supported chunk size: 60 MiB.
Handling Errors
Wrap the upload in a try-catch
block:
try { var uploadResult = await uploadTask.UploadAsync(); } catch (ServiceException ex) { Console.WriteLine($"Error: {ex.Message}"); }
Full Example
using Microsoft.Graph; using Azure.Identity; using System; using System.IO; using System.Threading.Tasks; class Program { static async Task Main() { var tenantId = "YOUR_TENANT_ID"; var clientId = "YOUR_CLIENT_ID"; var clientSecret = "YOUR_CLIENT_SECRET"; var credential = new ClientSecretCredential(tenantId, clientId, clientSecret); var graphClient = new GraphServiceClient(credential); var siteId = "contoso.sharepoint.com,abc123"; var driveId = "b!12345"; var fileName = "project-backup.zip"; var folderPath = "Shared%20Documents/Backups"; try { // Create session var uploadSession = await graphClient.Sites[siteId] .Drives[driveId] .Root .ItemWithPath($"{folderPath}/{fileName}") .CreateUploadSession() .Request() .PostAsync(); // Upload file using var fileStream = File.OpenRead("C:/backups/project-backup.zip"); var uploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, fileStream); var result = await uploadTask.UploadAsync(); Console.WriteLine(result.UploadSucceeded ? "Success!" : "Failed."); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } }
Troubleshooting Tips
Permissions: Ensure your app has
Sites.ReadWrite.All
in Azure AD.Path Encoding: Use
%20
for spaces in folder paths.Session Expiry: Upload sessions expire after 24 hours.
By following these steps, you can reliably upload massive files to SharePoint without timeouts or headaches. Happy uploading! 🚀
Post a Comment