I’m trying to upload files (.xlsx less than 4MB) into a drive location via MS Graph API.
Please see the below code for more details I appriciate your help to resolve the issue currently facing based on the URL. Error - Resource not found for the segment Oks.
public static string DecodeData(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}
// Upload files to SharePoint
public void SharePointUploadDriveItems(string accessToken)
{
var httpClient = new HttpClient();
try
{
string path = @"C:\\StockLevelReportLocation\\New Files\\TestFileUpload.xlsx";
byte[] filebytes = System.IO.File.ReadAllBytes(path);
using (var client = new HttpClient())
{
string fileName = "TestFileToUpload.txt";
using (var request = new HttpRequestMessage(HttpMethod.Put, "https://graph.microsoft.com/v1.0/drives/root/Oks/Stock Report/TestFileUpload.xlsx/content"))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Headers.Add("Accept", "application/json;odata.metadata=verbose");
request.Content = new StringContent(DecodeData(Convert.ToBase64String(filebytes)), System.Text.Encoding.ASCII, "text/plain");
var driveItemsResponse = httpClient.SendAsync(request).Result;
var driveItemsResponseContent = driveItemsResponse.Content.ReadAsStringAsync().Result;
}
}
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
Looks like you are missing :
at the beginning and at the end of the path in the URL. Another issue is that you didn't specify drive id
Your URL
https://graph.microsoft.com/v1.0/drives/root/Oks/Stock Report/TestFileUpload.xlsx/content
But it should be
https://graph.microsoft.com/v1.0/drives/{drive_id}/root:/Oks/Stock Report/TestFileUpload.xlsx:/content
Code
using (var request = new HttpRequestMessage(HttpMethod.Put, "https://graph.microsoft.com/v1.0/drives/{drive_id}/root:/Oks/Stock Report/TestFileUpload.xlsx:/content"))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Headers.Add("Accept", "application/json;odata.metadata=verbose");
request.Content = new StringContent(DecodeData(Convert.ToBase64String(filebytes)), System.Text.Encoding.ASCII, "text/plain");
var driveItemsResponse = httpClient.SendAsync(request).Result;
var driveItemsResponseContent = driveItemsResponse.Content.ReadAsStringAsync().Result;
}