Search code examples
c#restonedriverestsharp

Upload file to OneDrive using RestAPI


I am trying to upload an image to OneDrive using below code. The file was successfully uploaded to the OneDrive folder but when I download the file manually from OneDrive, it opens in black color and shows Invalid Image.

var client = new RestClient("https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content");
var request = new RestRequest(Method.PUT);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", Path.GetExtension(originalFileName).GetMimeType());
request.AddHeader("Authorization", "Bearer " + GetAccessToken());
request.AddFile("content", System.IO.File.ReadAllBytes(filePath), originalFileName);

var response = client.Execute(request);

I really do not know what mistake I am making in here. May you please help me?


Solution

  • Inspired from this SO answer

    I need to change it to HttpClient from RestClient. After change the code will like:

    using (var client = new HttpClient())
    {
        var url = "https://graph.microsoft.com/v1.0" + $"/drives/{driveID}/items/{folderId}:/{originalFileName}:/content";
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());
    
        byte[] sContents = System.IO.File.ReadAllBytes(filePath);
        var content = new ByteArrayContent(sContents);
    
        var response = client.PutAsync(url, content).Result.Content.ReadAsStringAsync().Result;
    }