I am using below Microsoft Graph API code to upload files to OneDrive for business of currently logged in user. The code uploads notepad .txt files fine and I can open file properly with content as it is. But when it uploads a .docx (word document), on opening attempt it throws error as file corrupted. What I am missing here? reference used - https://blog.mastykarz.nl/2-practical-tips-office-365-group-files-api/ https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/item_uploadcontent
Code:
byte[] filebytes= fileuploadControl.FileBytes;
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Put, "https://graph.microsoft.com/v1.0/me/drive/root/children/" + filename + "/content"))
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
request.Headers.Add("Accept", "application/json;odata.metadata=verbose");
request.Content = new StringContent(DecodeFrom64(Convert.ToBase64String(filebytes)),System.Text.Encoding.ASCII, "text/plain");
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode)
{
lblFileUpload.Text = "File uploaded successfully";
}
}
}
}
static public string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}