5,667,575 members and growing! (16,801 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

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

By madmik3

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!
C#, Windows, .NET 1.0, .NETVisual Studio, VS.NET2002, Dev

Posted: 19 Oct 2004
Updated: 19 Oct 2004
Views: 117,681
Bookmarked: 46 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
21 votes for this Article.
Popularity: 5.65 Rating: 4.27 out of 5
1 vote, 4.8%
1
1 vote, 4.8%
2
0 votes, 0.0%
3
2 votes, 9.5%
4
17 votes, 81.0%
5

Introduction

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>
</form>

You could run UploadFileEx like this:

CookieContainer cookies = new CookieContainer();
//add or use cookies

NameValueCollection querystring = new NameValueCollection();
querystring["uname"]="uname";
querystring["passwd"]="snake3";
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", 
     querystring,cookies);

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("--");
    sb.Append(boundary);
    sb.Append("\r\n");
    sb.Append("Content-Disposition: form-data; name=\"");
    sb.Append(fileFormName);
    sb.Append("\"; filename=\"");
    sb.Append(Path.GetFileName(uploadfile));
    sb.Append("\"");
    sb.Append("\r\n");
    sb.Append("Content-Type: ");
    sb.Append(contenttype);
    sb.Append("\r\n");
    sb.Append("\r\n");            

    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 + 
                                           boundaryBytes.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)fileStream.Length))];
    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:

<?php

print_r($_REQUEST);

$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. ";
}
else
{
    print "Possible file upload attack!  Here's some debugging info:\n";
    print_r($_FILES);
}
print "</PRE>";
?>

Credits...

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

License

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

madmik3



Location: United States United States

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 64 (Total in Forum: 64) (Refresh)FirstPrevNext
GeneralUpload string + file + stringmemberTravelster66112:25 19 Oct '08  
Generalform data and file uploadmembersyed wasif ali22:21 27 Jul '08  
Generalmore files not only one file to uploadmemberkappos3:23 12 Jun '08  
GeneralGracias excelente solucionmemberMember 31047895:29 10 Jun '08  
GeneralAs another commenter pointed out it's better to close the stream after you're donememberdolzenko9:01 1 Jun '08  
GeneralAny one know how to decode this type of postmembersmesser12:19 3 Jan '08  
QuestiongetResponse like a web browser?memberEnderwiggin11:44 14 Dec '07  
GeneralWhy it freezes sometimes at requestStream.Write(buffer, 0, bytesRead);?memberstaryon8:31 14 Nov '07  
GeneralThanksmembercreatorulcom13:11 5 Oct '07  
QuestionWebExceptionmembertobi_z13:49 7 Sep '07  
GeneralHow to send a file a attachmentmemberPhBV3:50 3 Sep '07  
GeneralParse error in PHP pagememberEdYellowMan5:20 22 May '07  
GeneralGreat Job!memberkkkwkk5:11 17 May '07  
GeneralGet error in Tomcatmemberfranciscomesa5:00 28 Apr '07  
GeneralerrorsmemberAaron Sulwer7:39 9 Aug '06  
GeneralIO.Exception, Cannot close stream until all bytes are writtenmemberinteresting.com.au21:15 27 Jul '06  
GeneralPlease Close() your files when done with them!!!memberFurroy5:45 19 Jul '06  
GeneralDid not work for mememberMRKKO7:26 17 May '06  
GeneralRe: Did not work for mememberMystic_4:59 20 May '06  
GeneralRe: Did not work for mememberAaron Sulwer11:29 2 Aug '06  
Generalpost data to http://www.codeproject.commemberMystic_22:06 27 Apr '06  
General2nd partmemberMystic_22:08 27 Apr '06  
QuestionGetting error as :(406) Not acceptable.memberRahul.P0:42 7 Apr '06  
GeneralWebClient with cookies now possible.memberkatokay6:08 25 Mar '06  
GeneralRe: WebClient with cookies now possible.memberu7pro5:33 2 Mar '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 19 Oct 2004
Editor: Smitha Vijayan
Copyright 2004 by madmik3
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project