Search code examples
c#httpposthttpwebrequestsystem.net.httpwebrequest

Sending a file via WebRequest


I need to use C# to send a file to with the content-type of application/octet stream.

I can create an HttpWebRequest like the below:

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://test.com");
            request.Headers.Add("content-type", "application/octet-stream");
            //Add file here?

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.Created)
            {
                Console.WriteLine("YAYA");
            }
            else
            {
                Console.WriteLine("OH NO MR BILL!!!!");
            }

How do I accomplish the addition of the file into my stream?


Solution

  • Just get the request stream and then copy from your source stream.

    using (var requestStream = request.GetRequestStream())
    {
        fileStream.CopyTo(requestStream);
    }