simulating input type = file from c# windows applicaiton

  • Thread starter Thread starter madmike
  • Start date Start date
M

madmike

hi,

I can't seem to find the right way to simulate a file form post to a
web page from a window applicaiton and it seems like there should be
an easy way. I can post form variable like this:

string strId = "id";
string strName = "name";

ASCIIEncoding encoding=new ASCIIEncoding();
string postData="p_word="+strId;
postData += ("&u_name="+strName);
byte[] data = encoding.GetBytes(postData);

// Prepare web request...
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("http://localhost/test.php");
myRequest.CookieContainer = new System.Net.CookieContainer(10000);
myRequest.Method = "POST";
myRequest.ContentType="application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream=myRequest.GetRequestStream();
// Send the data.
newStream.Write(data,0,data.Length);
newStream.Close();
WebResponse res = myRequest.GetResponse();
StreamReader sr = new StreamReader( res.GetResponseStream());
string s = sr.ReadToEnd();

Debug.WriteLine(s);

What do I need to do in order to simulate a input type = file field?

thanks in advance,
Mike
 
Mike,

You might want to try the WebClient class, and call the UploadFile
method. It should do what you are looking for.

Hope this helps.
 
Nicholas,

I looked at WebClient.FileUpload before and decided not to use it
because I knew I needed to set the cookie container as well as post
other form variables with the file. Am I wrong is assuming that
WebClient.FileUpload will not be able to do those things?

thanks,
Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top