Search code examples
office365officedev

Microsoft Graph API File upload in Onedrive for business


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

Solution

  • Below code worked for me perfectly. Code

    var fileUrl = new Uri("https://graph.microsoft.com/v1.0/me/drive/root/children/" + filename + "/content");
                        var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(fileUrl);
                        request.Method = "PUT";
                        request.ContentLength = filebytes.Length;
                        request.AllowWriteStreamBuffering = true;
                        //request.Accept = "application/json;odata=verbose";
                        request.ContentType = "text/plain";
                        request.Headers.Add("Authorization", "Bearer " + accessToken);
                        System.IO.Stream stream = request.GetRequestStream();
                        //filestream.CopyTo(stream);
                        stream.Write(filebytes, 0, filebytes.Length);
                        stream.Close();
    
                        System.Net.WebResponse response = request.GetResponse();