Send file+parameters in post request

m.qayyum picture m.qayyum · Aug 30, 2013 · Viewed 23.5k times · Source

I'm using this code to send parameters to a webpage and getting correct response from it.

System.Net.WebClient oWeb = new System.Net.WebClient();
oWeb.Proxy = System.Net.WebRequest.DefaultWebProxy;
oWeb.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
oWeb.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] bytArguments = System.Text.Encoding.ASCII.GetBytes("value1=123&value2=xyz");
byte[] bytRetData = oWeb.UploadData("http://website.com/file.php", "POST", bytArguments);
response = System.Text.Encoding.ASCII.GetString(bytRetData);

But now I want to send a file like (.doc) to it + above parameters(value1, value2), but I don't know how to do that.

Answer

Hamlet Hakobyan picture Hamlet Hakobyan · Aug 30, 2013

Use WebClient.QueryString to pass name/value pairs associated with the request.

NameValueCollection parameters = new NameValueCollection();
parameters.Add("value1", "123");
parameters.Add("value2", "xyz");
oWeb.QueryString = parameters;
var responseBytes = oWeb.UploadFile("http://website.com/file.php", "path to file");
string response = Encoding.ASCII.GetString(responseBytes);