Home > .Net, Code samples, c# > Uploading multiple files and form fields in .Net

Uploading multiple files and form fields in .Net

January 23rd, 2008

Recently while building a small application for a friend of mine I came across a part where I needed something that I just couldn’t find in the .Net framework. I needed to upload two files (and specify their fieldnames) and a few form fields to a webpage. I thought this would be easy just using the provided WebClient class but after looking closer at it I found that it didn’t really offer anything of what I needed. Trying not to feel let down by this I started to write my own extended version of WebClient with a few new tricks that the old one couldn’t do.

I tried to keep it as simple as possible so instead of writing new classes to hold form and file data I used two Dictionary<string, string> to pass the values. The Key is the fieldname and the Value the value or the path to the file. An example of uploading a few files and adding a few fields to that could look like this:

It doesn’t look that hard does it? It’s perfect to use if you need to “submit” a form on a webpage from your c# application or just need to send several files to a webserver in the same request. Below is the complete code for WebClientEx displayed. You may use it for anything you want as long as you don’t claim it as your own. If you use it in a project of yours then please write a comment or send me an email about it!

I won’t go in explaining line of this code as I’ve done in a few other samples. The code isn’t that hard to understand if you have moved beyond the “beginner stage” of coding. The thing worth mentioning is the part with MimeHelper.GetMimeTypeForExtension() which is a small function I wrote which checks the registry for any available mimetype for a given extension. I’ve included that code below aswell since it’s needed for WebClientEx.

Enjoy!

.Net, Code samples, c# , , , , , , , ,

  1. No comments yet.
  1. No trackbacks yet.