Search code examples
c#asp.netdynamics-crmdynamics-365

Issue with File Upload to Dynamics 365 CRM


I've used the following code to upload a file to Dynamics 365 CRM. However, after the upload, the file, originally named test.pdf appears in CRM as untitled.txt.

public async Task<bool> UploadFile(string entityName, string recordId, string columnName, string base64String)
{
        string baseUrl = $@"{serviceUrl}{entityName}({recordId})/{columnName}";

        using (var client = crmConfig.BuildClient())
        {
            client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
            client.DefaultRequestHeaders.Add("OData-Version", "4.0");
            
            string fileName = "test.pdf"; 
            string contentType = "application/octet-stream";
          
            byte[] fileBytes = Convert.FromBase64String(base64String);
            ByteArrayContent fileContent = new ByteArrayContent(fileBytes);

            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = fileName,
            };

            fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            HttpResponseMessage response = await client.PatchAsync(baseUrl, fileContent);

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("File uploaded successfully.");
                return true;
            }
            else
            {
                Console.WriteLine("Error uploading the file. Status code: " + response.StatusCode);
                return false;
            }
        }
}

Solution

  • I should have add the name of the file in the header. =>

    fileContent.Headers.Add("x-ms-file-name", fileFullName);