1
votes

I am trying to upload a file to Onedrive using RestSharp and Graph API. Basically I want to upload an Excel file. However, even the file saves, there is problem with the content. I am using:

https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent

using the code:

        string newToken = "bearer ourtoken";
        var client = new RestClient("https://xxx-my.sharepoint.com/_api/v2.0/"+ oneDrivePath + Path.GetFileName(filePathWithName) + ":/content");
        var request = new RestRequest(Method.PUT);
        request.RequestFormat = DataFormat.Json;
        request.AddHeader("Authorization", newToken);
        request.AddHeader("Content-Type", "text/plain");

        byte[] sContents;
        FileInfo fi = new FileInfo(filePathWithName);

        // Disk
        FileStream fs = new FileStream(filePathWithName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        sContents = br.ReadBytes((int)fi.Length);
        br.Close();
        fs.Close();

        request.AddBody(Convert.ToBase64String(sContents));

        var response = client.Execute(request);

This uploads the file however the XLSX file becomes corrupted.

Basically I need to figure out how to pass the stream to the RestSharp request.

1

1 Answers

0
votes

Solved it by changing RestClient to HttpClient.

 string newToken = "bearer mytoken"

        using (var client = new HttpClient())
        {
            var url = "https://xxx-my.sharepoint.com/_api/v2.0/" + oneDrivePath + Path.GetFileName(filePathWithName) + ":/content";
            client.DefaultRequestHeaders.Add("Authorization", newToken);


            byte[] sContents = File.ReadAllBytes(filePathWithName);
            var content = new ByteArrayContent(sContents);

            var response = client.PutAsync(url, content).Result;

            return response;

        }