Home » c# » Upload a File via WebRequest Using CSharp

Upload a File via WebRequest Using CSharp


I got this question a couple of weeks ago but just never had the time to put into answering fully.  But today I have some extra time due to the fact that I’m under-booked with projects.

The question went something like this:

“I want to be able to upload a file from a desktop application to a web site that has a form that accepts the file as a post.  How do I do that?”

And while I’ve done some things in the past that come close, I’ve never had to do this exact task.  But it does look interesting.

The entire trick to making this work is to make the web server think that the form has been filled out and that the post has been implemented.

To do this, you’ll need to create a WebRequest object and set some properties on it.  The two that you must set are the Method property (to POST) and the ContentType (to “multipart/form-data; boundary=”+boundary).  If you are sending multiple files, you’ll need multiple boundaries.

System.Net.WebRequest wr = 
    System.Net.WebRequest.Create("url goes here");
wr.ContentType = "multipart/form-data; boundary=xyz";
wr.Method = "POST";

To send data, we need to format the data in multipart/form-data mode.  First we retrieve the file into a stream.

FileStream fs= new FileStream("your file here",
    System.IO.FileMode.Open, System.IO.FileAccess.Read);
byteArray= new byte[loFile.Length];
fs.Read(byteArray,0,(int) byteArray.Length);

Then we setup the multipart boundary header.

string var = "--" + boundaryID + "\r\n"  +
     "Content-Disposition: form-data; name=\"" + Key + "\" filename=\"" +
      new FileInfo("your file here").Name + "\"\r\n\r\n";

Then we write the boundary header and the content to the output stream

System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms);

System.IO.Stream postStream = wr.GetRequestStream();

Note the last bw.Write() line is telling the server this is the  end of the boundary.

And then the final bit of code that sends it to the server and gets the resulting HTML.

System.Net.WebResponse wresponse = wr.GetResponse();
System.Text.Encoding enc = 
System.IO.StreamReader responseStream =
    new System.IO.StreamReader
        (wresponse.GetResponseStream(), enc);
string lcHtml = responseStream.ReadToEnd();

That’s all there is to it.  Once you know how to do it, it is rather simple.

Other places talking about WebRequest using multipart/form-data

Brian Grinstead » Blog Archive » Multipart Form Post in C# – So, I needed to roll my own form post. Here is the Multipart Form RFC and the W3C Specification for multipart/form data. After reading these links and searching some forums, here is what I came up with. ….. userAgent, contentType, formData) End Function Private Function PostForm(ByVal postUrl As String, _ ByVal userAgent As String, _ ByVal contentType As String, _ ByVal formData As Byte()) _ As HttpWebResponse Try Dim request As HttpWebRequest = WebRequest. …

Retrieving HTTP content in .NET with WebRequest/WebResponse – This code finalizes the request for POST data by checking whether we’ve already written something into the POST buffer and if so configuring the POST request by specifying the content type. In the case of multi-part form POST an …


Other post in c#

Related Post

  • Test Sending Email without a Server in ASP.NETTest Sending Email without a Server in ASP.NET By now, most people are familiar with the fact that ASP.NET will send mail from the codebehind by simply adding a few lines to your web.config file and adding another few lines of code in […]
  • CefSharp Offscreen [Why do I have so many instances of Chromium?]CefSharp Offscreen [Why do I have so many instances of Chromium?] I’ve been using the CefSharp.Offscreen library to drive the Chromium browser for a couple of months now.  While the code I’ve been working on has been working correctly, I could never […]
  • Serializable attribute vs Serializable InterfaceSerializable attribute vs Serializable Interface Judging from the comments I received yesterday, it looks like we need to review  serialization in .NET. The Easy Way There are two ways of making an object serializable.  The […]
  • ASP.NET Dynamic ValidatorASP.NET Dynamic Validator One of the controls that was added to ASP.NET 3.5 in the SP1 release was the Dynamic Validator control. I completely missed it. What it does is pretty cool.  But it doesn’t […]
  • C# Properties Get and SetC# Properties Get and Set My son is learning to program.  Last week he asked me to explain C# properties get and set and, as it turns out, it looks like many others are asking for the same.  So, I’ve decided to […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer focusing on ASP.NET, C#, Node.js, JavaScript, HTML, CSS, BootStrap, and Angular.JS. Does your team need additional help in any of the above? Contact Dave today.

One Pingback/Trackback