File Upload with HttpWebRequest doesn't post the file

Posted by Sri Kumar on Stack Overflow See other posts from Stack Overflow or by Sri Kumar
Published on 2010-06-17T11:26:18Z Indexed on 2010/06/17 11:43 UTC
Read the original article Hit count: 610

Hello All,

Here is my code to post the file. I use asp fileupload control to get the file stream.

HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://localhost:2518/Web/CrossPage.aspx");
requestToSender.Method = "POST";
requestToSender.ContentType = "multipart/form-data";
requestToSender.KeepAlive = true;
requestToSender.Credentials = System.Net.CredentialCache.DefaultCredentials;
requestToSender.ContentLength = BtnUpload.PostedFile.ContentLength;

BinaryReader binaryReader = new BinaryReader(BtnUpload.PostedFile.InputStream);
byte[] binData = binaryReader.ReadBytes(BtnUpload.PostedFile.ContentLength);


Stream requestStream = requestToSender.GetRequestStream();
requestStream.Write(binData, 0, binData.Length);
requestStream.Close();

HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;

using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
 {
  fromSender = responseReader.ReadToEnd();
 }
XMLString.Text = fromSender;

In the page load of CrossPage.aspx i have the following code

 NameValueCollection postPageCollection = Request.Form;

 foreach (string name in postPageCollection.AllKeys)
  {
   Response.Write(name + " " + postPageCollection[name]);
  }

 HttpFileCollection postCollection = Request.Files;
 foreach (string name in postCollection.AllKeys)
 {
   HttpPostedFile aFile = postCollection[name];
   aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName));
 }
 string strxml = "sample";

 Response.Clear();
 Response.Write(strxml);

I don't get the file in Request.Files. The byte array is created. What was wrong with my HttpWebRequest?

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about fileupload