Web forms are submitted in one of two formats: application/x-www-form-urlencoded and multipart/form-data.
WebClient provides a very simple and convenient way to upload any kind of data to a website. In case of application/x-www-form-urlencoded all you have to do is to provide a NameValueCollection. In case of multipart/form-data, AFAIK, you have to create the request data yourself (which may include both files and name value pairs).
application/x-www-form-urlencoded
NameValueCollection formData = new NameValueCollection();
formData["q"] = "c# webclient post urlencoded";
formData["btnG"] = "Google Search";
formData["hl"] = "en";
WebClient myWebClient = new WebClient();
myWebClient.UploadValues(uriString, formData);
WebClient.UploadValues sets the HTTP method to "POST"
and the Content-Type to "application/x-www-form-urlencoded"
, URL-encodes formData
and uploads it to the specified uriString
.
multipart/form-data
string formData = @"--AaB03x
Content-Disposition: form-data; name=""submit-name""
Larry
--AaB03x
Content-Disposition: form-data; name=""files""; filename=""file1.dat""
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
" + Convert.ToBase64String(
File.ReadAllBytes("file1.dat"), Base64FormattingOptions.InsertLineBreaks) + @"
--AaB03x--
";
WebClient myWebClient = new WebClient();
myWebClient.Encoding = Encoding.ASCII;
myWebClient.Headers.Add("Content-Type", "multipart/form-data; boundary=AaB03x");
myWebClient.UploadString(uriString, formData);
This sets the Content-Type to "multipart/form-data"
with the boundary used in the request data.
WebClient.UploadData sets the HTTP method to "POST"
and uploads the byte array to the uriString
.
The request data in this example contains a file file1.dat
and a form parameter submit-name
which is set to Larry
.
The format is described in RFC2388.