使用Graph API使用C#上传到Onedrive [英] Upload to Onedrive with C# using Graph API

查看:177
本文介绍了使用Graph API使用C#上传到Onedrive的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用RestSharp和Graph API将文件上传到Onedrive.基本上我想上传一个Excel文件.但是,即使文件保存,内容也有问题.我正在使用:

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

使用代码:

        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);

这将上传文件,但是XLSX文件已损坏.

This uploads the file however the XLSX file becomes corrupted.

基本上,我需要弄清楚如何将流传递给RestSharp请求.

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

推荐答案

通过将RestClient更改为HttpClient来解决.

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;

        }

这篇关于使用Graph API使用C#上传到Onedrive的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆