Hi @gokulnath palani,
This Microsoft Learn module demonstrates how to upload both small and large files to SharePoint Online using Microsoft Graph.
Access Files with Microsoft Graph
The code to upload a small file is relatively simple.
var fileName = "smallfile.txt";
var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);
Console.WriteLine("Uploading file: " + fileName);
FileStream fileStream = new FileStream(filePath, FileMode.Open);
var uploadedFile = client.Me.Drive.Root
.ItemWithPath("smallfile.txt")
.Content
.Request()
.PutAsync<DriveItem>(fileStream)
.Result;
Console.WriteLine("File uploaded to: " + uploadedFile.WebUrl);
The code to upload a larger file requires chunking.
var fileName = "largefile.zip";
var filePath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);
Console.WriteLine("Uploading file: " + fileName);
// load resource as a stream
using (Stream stream = new FileStream(filePath, FileMode.Open))
{
var uploadSession = client.Me.Drive.Root
.ItemWithPath(fileName)
.CreateUploadSession()
.Request()
.PostAsync()
.Result;
// create upload task
var maxChunkSize = 320 * 1024;
var largeUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, stream, maxChunkSize);
// create progress implementation
IProgress<long> uploadProgress = new Progress<long>(uploadBytes =>
{
Console.WriteLine($"Uploaded {uploadBytes} bytes of {stream.Length} bytes");
});
// upload file
UploadResult<DriveItem> uploadResult = largeUploadTask.UploadAsync(uploadProgress).Result;
if (uploadResult.UploadSucceeded)
{
Console.WriteLine("File uploaded to user's OneDrive root folder.");
}
}
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.