Upload to Onedrive with C# using Graph API

别来无恙 提交于 2019-12-08 04:20:01

问题


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:


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;

        }


来源:https://stackoverflow.com/questions/39214692/upload-to-onedrive-with-c-sharp-using-graph-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!