[英]Upload to Onedrive with C# using Graph API
I am trying to upload a file to Onedrive using RestSharp and Graph API. 我正在尝试使用RestSharp和Graph API将文件上传到Onedrive。 Basically I want to upload an Excel file.
基本上我想上传一个Excel文件。 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 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. 这会上传文件,但XLSX文件已损坏。
Basically I need to figure out how to pass the stream to the RestSharp request. 基本上我需要弄清楚如何将流传递给RestSharp请求。
Solved it by changing RestClient to HttpClient. 通过将RestClient更改为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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.