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


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()
                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);
                return response.Content;

            catch (Exception ex)
                return ex.Message;


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, 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?