How to get the file extension of a downloaded file in One Drive Graph API

Viewed 21

I have written a console app in c# following this tutorial: https://docs.microsoft.com/en-gb/training/modules/msgraph-access-file-data/3-exercise-access-files-onedrive

Now when I download a file from my OneDrive via the console app using Microsoft Graph API, all the files get downloaded in type "File". However, the files are of type "Docx".

So how do I ensure that the files get downloaded in their original extension format? (.docx, .ppt, .csv, etc.)

var fileId = "01HLTXGBVIH3R6ILTKF5FKB2EMZKFG3MQ6";
var request = client.Me.Drive.Items[fileId].Content.Request();

var stream = request.GetAsync().Result;
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "driveItem_" + fileId + ".file");
var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);
1 Answers

Make a request to get file and read name property which represents the name of the item (filename and extension).

var fileId = "01HLTXGBVIH3R6ILTKF5FKB2EMZKFG3MQ6";
// make a request to get the file
var file = client.Me.Drive.Items[fileId].Request().GetAsync().Result;
var fileName = file.Name;

var request = client.Me.Drive.Items[fileId].Content.Request();

var stream = request.GetAsync().Result;
// create a file with the same name
var driveItemPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), fileName);

var driveItemFile = System.IO.File.Create(driveItemPath);
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(driveItemFile);
Console.WriteLine("Saved file to: " + driveItemPath);
Related