Upload a File via WebRequest Using CSharp

G03A0085

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);
fs.Close();

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);
bw.Write(Encoding.GetEncoding(1252).GetBytes(var));
bw.Write(byteArray);
bw.Write(Encoding.GetEncoding(1252).GetBytes("\r\n"));

System.IO.Stream postStream = wr.GetRequestStream();
ms.WriteTo(postStream);
postStream.Close();

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.Text.Encoding.GetEncoding(1252);
System.IO.StreamReader responseStream =
    new System.IO.StreamReader
        (wresponse.GetResponseStream(), enc);
string lcHtml = responseStream.ReadToEnd();
wresponse.Close();
responseStream.Close();

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 …

Like this Article? Subscribe to get every article sent to your email.

Related Post

  • ASP.NET Authentication – Multiple Domains w/ Same ApplicationASP.NET Authentication – Multiple Domains w/ Same Application In our series about ASP.NET authentication so far we’ve covered all the rather normal cases where you’d want to have the ability to log into different domains attached to the same […]
  • .NET Image Scaling in CSharp.NET Image Scaling in CSharp One feature of .NET that I use regularly is image scaling.  I typically use this on web sites that need image upload capabilities.  I assume the user is going to send me an […]
  • Why ASP.NET Changes Don’t Change AnythingWhy ASP.NET Changes Don’t Change Anything Has this happened to you? You make a change to a codebehind file or a web.config file and you rerun the application to see the effect and there is no change from the previous […]
  • FormView Edit and AddFormView Edit and Add The FormView generally makes editing a record at a time pretty easy.  However, one of the biggest problems I've seen with this control is that there is no way of telling the FormView […]
  • Forms Authentication – Creating UsersForms Authentication – Creating Users Last week we installed the tables into our database and set up the database connection so that we could implement forms based authentication. This week, we need to put into place a way […]

About Dave Bush

Dave Bush is a .NET programmer and Certified ScrumMaster who is passionate about managing risk as it relates to developing software. When he is not writing or speaking about topics related to Application Lifecycle Risk Management (ALRM), he is an example to his peers as he develops web sites in the ASP.NET environment using industry best practices.

One Pingback/Trackback

Awards & Certs