Click here to Skip to main content
12,821,670 members (38,224 online)
Click here to Skip to main content
Add your own
alternative version


30 bookmarked
Posted 13 Apr 2010

C# File Upload with form fields, cookies and headers

, 18 Apr 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Full featured HTTP upload utility

In it's most basic form, uploading a file or other data to an HTTP form handler using managed code is quite simple using the System.Net.WebClient class.

Listing 1: SimpleWebClientUpload

public void SimpleWebClientUpload()
    string filePath = Path.GetFullPath("TestFiles/TextFile1.txt");
    var client = new WebClient();   
    client.UploadFile("http://localhost/myhandler.ashx", filePath);

It is a common case that some cookies need to be maintained between requests or perhaps a header needs to be added to the request. This is possible using the WebClient class but the technique is not immediately obvious.

The trick is to create a class that inherits WebClient and overrides WebClient.GetWebRequest.

You can then add your cookies or headers to the request before it is sent.

Listing 2: CustomWebClient

// usage example 

string filePath = Path.GetFullPath("TestFiles/TextFile1.txt");

// possibly an existing CookieContainer containing authentication
// or session cookies
var cookies = new CookieContainer();

var client = new CustomWebClient(cookies);

// existing cookies are sent
client.UploadFile(_postHandlerUri, filePath);

// cookies is an instance of a reference type so it now
// contains updated/new cookies resulting from the upload   

public class CustomWebClient : WebClient
    private CookieContainer _cookies;

    public CustomWebClient(CookieContainer cookies)
        _cookies = cookies;

    protected override WebRequest GetWebRequest(Uri address)
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = _cookies;
        return request;

If this fulfills your requirements, then you are good to go.

Unfortunately, most file upload scenarios are HTML form based and may contain form fields in addition to the file data. This is where WebClient falls flat. After review of the source code for WebClient, it is obvious that there is no possibility of reusing it to perform a file upload including additional form fields.

So, the only option is to create a custom implementation that conforms to rfc1867, rfc2388 and the W3C multipart/form-data specification that will enable file upload with additional form fields and exposes control of cookies and headers.

Enumeration of the details of the implementation are beyond the intended scope of this posting, but the references are linked above and the code is quite brief and clear so to those interested, the process should be clear.

Note: This class is an excerpt from a slightly larger library, Salient.Web.HttpLib.HttpRequestUtility, that contains, amongst other functionality, many convenience overloads that eliminate unused parameters you can see in the usage implementation.

Listing 3: Upload example usage

using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;

/// <span class="code-SummaryComment"><summary>

Listing 4: Upload.cs

// /*!
//  * Project: Salient.Web.HttpLib
//  *
//  *
//  * Date: April 11 2010 
//  */


using System;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.Win32;


/// <span class="code-SummaryComment"><summary>

Using this class, you can easily post file data and form fields to form handlers and have full control of the cookies and headers that are sent/received.

Full implementation and tests can be found at

An alternate implementation of this code with a working Visual Studio 2008 solution can be found @


  • 04-18-2010 Removed licensing restriction 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Sky Sanders
Software Developer (Senior) Salient Solutions
United States United States
My name is Sky Sanders and I am an end-to-end, front-to-back software solutions architect with more than 20 years experience in IT infrastructure and software development, the last 10 years being focused primarily on the Microsoft .NET platform.

My motto is 'I solve problems.' and I am currently available for hire.

I can be contacted at

You may also be interested in...

Comments and Discussions

QuestionCode missing? Pin
Uldis Rāts21-Sep-16 0:57
professionalUldis Rāts21-Sep-16 0:57 
QuestionI'm get error Pin
Tran Van Huy11-Jan-13 16:59
memberTran Van Huy11-Jan-13 16:59 
GeneralProgress Pin
Laserson26-Nov-10 1:22
memberLaserson26-Nov-10 1:22 
Is it possible to handle uploading process? Thanks
GeneralRe: Progress Pin
Sky Sanders26-Nov-10 1:25
memberSky Sanders26-Nov-10 1:25 
GeneralGreat Work Except for the license Pin
icetea9418-Apr-10 4:02
membericetea9418-Apr-10 4:02 
GeneralRe: Great Work Except for the license Pin
Sky Sanders18-Apr-10 7:22
memberSky Sanders18-Apr-10 7:22 
GeneralGreat work Pin
Brij16-Apr-10 8:26
mentorBrij16-Apr-10 8:26 
GeneralRe: Great work Pin
Sky Sanders17-Apr-10 5:56
memberSky Sanders17-Apr-10 5:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 18 Apr 2010
Article Copyright 2010 by Sky Sanders
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid