[SOLVED] C# – Send a file in the body of an http request using RestRequest

Issue

This Content is from Stack Overflow. Question asked by M Wel

I tried sending an xlsx file (from path) in the body of a POST http request.
I was able to send the file but it arrived as a corrupted file.(I have no way to try to check what’s the issue on the api, because it’s a api like Amazon etc.)
this is the code I tried:

    public async Task<string> PostPostman()
        {
         try
            {
                string filePath = @"D:example2.xlsx";

                FileStream fs = File.OpenRead(filePath);
                var streamContent = new StreamContent(fs);
                streamContent.Headers.Add("Content-Type", "application/xlsx");
                var client = new RestClient("https://api.xxx.com/v1/FileUpload");
                var request = new RestRequest(Method.Post.ToString());
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/xlsx");
                request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
                request.AddParameter("application/xlsx", streamContent.ReadAsStringAsync().Result, ParameterType.RequestBody);
                RestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
                return response.Content;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return ex.Message;
            }
        }



Solution

I found the issue was that ReadAsStringAsync() opened the file but didn’t close it.

The solution I found is to send the file with File.ReadAllBytes(filePath) which reads the file and closes it back.

This is the final code:

public async Task<string> PostPostman()//found the code from the postman request I sent
        {
            try
            {
                string filePath = @"D:\example2.xlsx";

                var client = new RestClient("https://api.xxx.com/v1/FileUpload");
                var request = new RestRequest(Method.Post.ToString());
                request.Method = Method.Post;
                request.AddHeader("Content-Type", "application/xlsx");
                request.AddHeader("Authorization", "Bearer xxxxxxxxxxxxx");
                request.AddParameter("application/xlsx", File.ReadAllBytes(filePath), ParameterType.RequestBody);
                RestResponse response = client.Execute(request);
                Console.WriteLine(response.Content);
                return response.Content;

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return ex.Message;
            }
        }


This Question was asked in StackOverflow by M Wel and Answered by M Wel It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?