Click here to Skip to main content
Click here to Skip to main content

UploadFileEx: C#'s WebClient.UploadFile with more functionality

, 19 Oct 2004
Rate this:
Please Sign up or sign in to vote.
UploadFile hides some of the things you might need to get your Windows client simulating forms with file input fields. UploadFileEx gives you more control where you need it!


Okay, so you like the idea behind WebClient's UploadFile function, but you can't get it to do all the things you want? That's were I was at a week ago. This is what I learned in the past week. UploadFile seems good enough on the surface but you can run into some tricky things fast, like if you have some cookies to manage or you want to specify the content type, or change the name of the file input in the form? Well, this function will take care of those problems and should make simulating a web form with input type=file as easy as pi, er.. pie. Under the hood is a HttpWebRequest version of UploadFile that you could use to add additional functionality.

For example...

You would like to simulate this web form from your C# application:

<form action ="http://localhost/test.php" method = POST>
<input type = text name = uname>
<input type = password name =passwd>
<input type = FILE name = uploadfile>
<input type=submit>

You could run UploadFileEx like this:

CookieContainer cookies = new CookieContainer();
//add or use cookies
NameValueCollection querystring = new NameValueCollection();
string uploadfile;// set to file to upload
uploadfile = "c:\\test.jpg";

//everything except upload file and url can be left blank if needed
string outdata = UploadFileEx(uploadfile, 
     "http://localhost/test.php","uploadfile", "image/pjpeg", 

So on to the code...

So, this is UploadFileEx:

public static string UploadFileEx( string uploadfile, string url, 
    string fileFormName, string contenttype,NameValueCollection querystring, 
    CookieContainer cookies)
    if( (fileFormName== null) ||
        (fileFormName.Length ==0))
        fileFormName = "file";

    if( (contenttype== null) ||
        (contenttype.Length ==0))
        contenttype = "application/octet-stream";

    string postdata;
    postdata = "?";
    if (querystring!=null)
        foreach(string key in querystring.Keys)
            postdata+= key +"=" + querystring.Get(key)+"&";
    Uri uri = new Uri(url+postdata);

    string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
    webrequest.CookieContainer = cookies;
    webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
    webrequest.Method = "POST";

    // Build up the post message header
    StringBuilder sb = new StringBuilder();
    sb.Append("Content-Disposition: form-data; name=\"");
    sb.Append("\"; filename=\"");
    sb.Append("Content-Type: ");

    string postHeader = sb.ToString();
    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

    // Build the trailing boundary string as a byte array
    // ensuring the boundary appears on a line by itself
    byte[] boundaryBytes = 
           Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    FileStream fileStream = new FileStream(uploadfile, 
                                FileMode.Open, FileAccess.Read);
    long length = postHeaderBytes.Length + fileStream.Length + 
    webrequest.ContentLength = length;

    Stream requestStream = webrequest.GetRequestStream();

    // Write out our post header
    requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

    // Write out the file contents
    byte[] buffer = new Byte[checked((uint)Math.Min(4096, 
    int bytesRead = 0;
    while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
        requestStream.Write(buffer, 0, bytesRead);

    // Write out the trailing boundary
    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
    WebResponse responce = webrequest.GetResponse();
    Stream s = responce.GetResponseStream();
    StreamReader sr = new StreamReader(s);

    return sr.ReadToEnd();

This might help too..

You can handle the post in various ways but this is the PHP file I wrote to test:



$uploadDir = '%SOMEPATH';
$uploadFile = $uploadDir . $_FILES['userfile']['name'];
print "<PRE>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadFile))
    print "File is valid, and was successfully uploaded. ";
    print "Possible file upload attack!  Here's some debugging info:\n";
print "</PRE>";


I found most of this out by trial and error searching the web. One major source of this information was this article.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author


United States United States
No Biography provided

Comments and Discussions

Generalerrors PinmemberAaron Sulwer9-Aug-06 7:39 
GeneralIO.Exception, Cannot close stream until all bytes are written 21:15 
GeneralPlease Close() your files when done with them!!! PinmemberFurroy19-Jul-06 5:45 
GeneralDid not work for me PinmemberMRKKO17-May-06 7:26 
GeneralRe: Did not work for me PinmemberMystic_20-May-06 4:59 
GeneralRe: Did not work for me PinmemberAaron Sulwer2-Aug-06 11:29 
Generalpost data to PinmemberMystic_27-Apr-06 22:06 
General2nd part PinmemberMystic_27-Apr-06 22:08 
WebHeaderCollection headers = webresponse.Headers;
if ((webresponse.StatusCode == HttpStatusCode.Found) ||
(webresponse.StatusCode == HttpStatusCode.Redirect) ||
(webresponse.StatusCode == HttpStatusCode.Moved) ||
(webresponse.StatusCode == HttpStatusCode.MovedPermanently))
{ // Get redirected uri
uri2 = headers["Location"] ;
uri2 = uri2.Trim();
//Check for any cookies
if (headers["Set-Cookie"] != null)
{Cookie = headers["Set-Cookie"];
string ReUri =uri2
//Check if there is any redirected URI.
ReUri = ReUri.Trim();
if (ReUri.Length == 0) //No redirection URI
{ReUri = uri;
NameValueCollection collHeader = new NameValueCollection();
if (Cookie.Length > 0)
webrequest=null; webrequest = (HttpWebRequest)WebRequest.Create(ReUri);
webrequest.KeepAlive = true;
webrequest.Method = RequestMethod;
webrequest.Accept = "*/*";
webrequest.AllowAutoRedirect = false;
webrequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; " + "Windows NT 5.0;SV1;.NET CLR 1.1.4322)";
webrequest.ContentLength = Request.Length;
webrequest.ContentType = "text/html";
int iCount2 = collHeader.Count;
string key2;
string keyvalue2;
for (int i2=0; i2 < iCount2; i2++)
{ key2 = collHeader.Keys[i2];
keyvalue2 = collHeader[i2];
webrequest.Headers.Add(key2, keyvalue2);
webrequest.Credentials = wrCache;
BuildReqStream(ref webrequest);
webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);
string Response = loResponseStream.ReadToEnd();
}//End of Try Block
catch (WebException e)
catch (System.Exception e)
System.IO.FileStream strr=new FileStream("C:\\itsnew.html",FileMode.Append);
byte[] bt=Encoding.GetEncoding(1252).GetBytes(Response);
} //End of SendRequestTo method

private void BuildReqStream(ref HttpWebRequest webrequest)
//This method build the request stream for WebRequest
byte[] bytes = Encoding.ASCII.GetBytes(Request);
Stream oStreamOut = webrequest.GetRequestStream();
}//End BuildReqStream method

QuestionGetting error as :(406) Not acceptable. PinmemberRahul.P7-Apr-06 0:42 
GeneralWebClient with cookies now possible. Pinmemberkatokay25-Mar-06 6:08 
GeneralRe: WebClient with cookies now possible. Pinmemberu7pro2-Mar-07 5:33 
GeneralRe: WebClient with cookies now possible. Pinmemberkatokay2-Mar-07 6:28 
QuestionRe: WebClient with cookies now possible. PinmemberNickHD22-Apr-07 3:28 
QuestionRe: WebClient with cookies now possible. PinmemberNooklez19-Jun-07 0:37 
AnswerRe: WebClient with cookies now possible. (Wrong) PinmemberAbsolute Solutions11-Jul-07 21:46 
GeneralPOST data Pinmembermorecraf1-Mar-06 5:21 
GeneralRe: POST data Pinmembersatyajeeth20-Feb-07 2:01 
GeneralClosing Boundary Error PinmemberNick Lucas16-Dec-05 6:02 
GeneralRe: Closing Boundary Error PinmemberKartik Ganesan29-Nov-06 12:18 
GeneralProxy problems PinmemberKriG23-Nov-05 3:02 
Generaldon't know how to resolve this error Pinmemberwarenbe10-Nov-05 13:57 
GeneralRe: don't know how to resolve this error 21:14 
GeneralRe: don't know how to resolve this error Pinmemberwarenbe28-Jul-06 1:22 
GeneralRe: don't know how to resolve this error PinmemberMancrut deeeee17-Nov-06 20:19 
Questioncan we asp file instead of php file Pinmemberpayoshini23-May-05 20:45 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141223.1 | Last Updated 20 Oct 2004
Article Copyright 2004 by madmik3
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid