0

i have one issue for posting file content to another web page. here is my code:

Dim postData As String = "name=NAME2&dob=21/09/1991&add1=ADD11&add2=ADD22&city=CITY2&area=AREA2&state=STATE2&emailID=EMAILID2&Pin=380008&mobile=1234567890&IsNRI=False&stateId=1&categoryId=1&CategoryName=Test&FilePath=D:%9%SHALIN%9%HOW TO INSTALL WEBSITE TO IIS.docx"
        Dim tempCookies As New CookieContainer
        Dim encoding As New UTF8Encoding
        Dim byteData As Byte() = encoding.GetBytes(postData)
        Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://localhost:29478/AddressBook/Default.aspx"), HttpWebRequest)
        postReq.Method = "POST"
        postReq.KeepAlive = True
        postReq.CookieContainer = tempCookies
        postReq.ContentType = "multipart/form-data"
        postReq.Referer = "http://localhost:29478/AddressBook/Default.aspx"
        postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"
        postReq.ContentLength = byteData.Length
        postReq.UseDefaultCredentials = True
        postReq.PreAuthenticate = True
        postReq.Credentials = CredentialCache.DefaultCredentials
        'Dim status As Boolean = True
        'status = System.IO.File.Exists("D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")
        'If status = True Then
        '    Console.WriteLine("Exists")
        'Else
        '    Console.WriteLine("Not Exists")
        'End If
        Dim wc As WebClient
        wc = New WebClient
        wc.UseDefaultCredentials = True
        wc.Credentials = CredentialCache.DefaultCredentials
        wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2")
        'wc.Headers.Add("Content-Disposition: form-data; name='files'; filename='HOW TO INSTALL WEBSITE TO IIS.docx'")
        wc.UploadFile(DirectCast(New Uri("http://localhost:29478/AddressBook/UploadFiles"), Uri), "PUT", "D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")
        wc.Dispose()
        Dim postreqstream As Stream = postReq.GetRequestStream()
        postreqstream.Write(byteData, 0, byteData.Length)
        postreqstream.Close()
        Dim postresponse As HttpWebResponse
        postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
        tempCookies.Add(postresponse.Cookies)
        logincookie = tempCookies
        Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
        Dim thepage As String = postreqreader.ReadToEnd

and at page receiver i have this code :

protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            pnlGrid.Visible = true;
            pnlEntry.Visible = false;
            pnlReport.Visible = false;
            GridView1.DataBind();
        }
        string name = null, dob = null, add1 = null, add2 = null, city = null, area = null, state = null, emailID = null, Pin = null, Mobile = null, IsNRI = null, stateId = null, categoryId = null, categoryname = null, FilePath = null;
        name = Request.Form["name"];
        dob = Request.Form["dob"];
        add1 = Request.Form["add1"];
        add2 = Request.Form["add2"];
        city = Request.Form["city"];
        area = Request.Form["area"];
        state = Request.Form["state"];
        emailID = Request.Form["emailID"];
        Pin = Request.Form["Pin"];
        Mobile = Request.Form["mobile"];
        IsNRI = Request.Form["IsNRI"];
        stateId = Request.Form["stateId"];
        categoryId = Request.Form["categoryId"];
        categoryname = Request.Form["CategoryName"];
        FilePath = Request.Form["FilePath"];
        if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(dob) && !string.IsNullOrEmpty(add1) && !string.IsNullOrEmpty(add2) && !string.IsNullOrEmpty(city) && !string.IsNullOrEmpty(area) && !string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(emailID) && !string.IsNullOrEmpty(Pin) && !string.IsNullOrEmpty(Mobile) && !string.IsNullOrEmpty(IsNRI) && !string.IsNullOrEmpty(state) && !string.IsNullOrEmpty(categoryId) && !string.IsNullOrEmpty(categoryname) && !string.IsNullOrEmpty(FilePath))
        {
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                bool IsNrI = false;
                if (IsNRI.Equals("True"))
                {
                    IsNrI = true;
                }
                else
                {
                    IsNrI = false;
                }
                ADD myAdd = new ADD();
                myAdd.Name = name;
                myAdd.Dob = DateTime.ParseExact(dob, "dd/MM/yyyy", null);
                myAdd.Add1 = add1;
                myAdd.Add2 = add2;
                myAdd.City = city;
                myAdd.Area = area;
                myAdd.State = state;
                myAdd.Pin = Pin;
                myAdd.Mobile = Mobile;
                myAdd.EmailID = emailID;
                myAdd.IsNRI = IsNrI;
                myAdd.StateId = int.Parse(stateId);
                myAdd.CategoryID = int.Parse(categoryId);
                myAdd.CategoryName = categoryname;
                db.ADDs.InsertOnSubmit(myAdd);
                db.SubmitChanges();
                int newId = myAdd.TabId;
                if (newId > 0)
                {
                    pnlGrid.Visible = true;
                    pnlEntry.Visible = false;
                    GridView1.DataBind();
                    Literal2.Text = "Record Inserted Successfully!";
                    UpdatePanel1.Update();
                }
            }
            FileUpload1.SaveAs(Server.MapPath("~/UploadFiles/" + Request.Files["files"].FileName));
        }
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }

here i can't receive file from web client. what can i do?

*************Updated****************

wc.UploadFile(DirectCast(New Uri("http://localhost:29478/AddressBook/UploadFiles"), Uri), "POST", "D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")


The underlying connection was closed: An unexpected error occurred on a receive.

Second Trick :

 Dim wc As WebClient
            wc = New WebClient
            wc.UseDefaultCredentials = True
            wc.Credentials = CredentialCache.DefaultCredentials
            wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2")
            wc.UploadFileAsync(DirectCast(New Uri("http://localhost:29478/AddressBook/UploadFiles"), Uri), "POST", "D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")
            wc.Dispose()

How ever this code works fine but not getting file at aspx page

        foreach (string f in Request.Files.AllKeys)
        {
            HttpPostedFile file = Request.Files[f];
            file.SaveAs(Server.MapPath("~/UploadFiles/" + file.FileName));
        }
Gajjar Shalin
  • 95
  • 1
  • 11
  • You can send file at webservices – rdn87 Jan 07 '16 at 13:08
  • What a mess...please try to clean it up. Why would you want to post the file to a webform from code? Please describe your use case, what your are trying to do might be done but there are other (more convenient) ways of doing this. – mortb Jan 07 '16 at 14:03

1 Answers1

1

Here is a very simplified code piece which shows how to send a file to a webpage:

C# for sending

WebClient myWebClient = new WebClient();

string fileName = "path to file 2 send";
string uriString = "url asp page 2 receive";

byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

ASP.NET page

<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {

    foreach(string f in Request.Files.AllKeys) {
        HttpPostedFile file = Request.Files[f];
        file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
    }   
}

</Script>
<html>
<body>
<p> Upload complete.  </p>
</body>
</html>

Src: https://msdn.microsoft.com/en-us/library/36s52zhs(v=vs.110).aspx

Asons
  • 84,923
  • 12
  • 110
  • 165
  • I use this code but still i'm getting this error see update. – Gajjar Shalin Jan 08 '16 at 07:58
  • Can't see any update. Have you updated your question yet? – Asons Jan 08 '16 at 08:04
  • @GajjarShalin I tested my answer and it works. You appear to have some other kind of error and that is a completely different question, so please add that as a new question, with that new code you use, and we can have a look at that. – Asons Jan 08 '16 at 08:30
  • @GajjarShalin I also see one thing which appears wrong. You can't have `"POST"` in this line: `wc.UploadFile(DirectCast(New Uri("http://localhost:29478/AddressBook/UploadFiles"), Uri), "POST", "D:\SHALIN\HOW TO INSTALL WEBSITE TO IIS.docx")`. It should only be the url and the file. – Asons Jan 08 '16 at 08:33
  • I understand ur logic but i have small problem while it can't sends files to another web page with onyl string like file how ever i can't post files with postReq.ContentType = "multipart/form-data" and another thing is postReq.ContentType = "application/x-www-form-urlencoded". How ever i can't sent file with second content type. If i use first then i can't send data's to another page. please help me... – Gajjar Shalin Jan 11 '16 at 05:26
  • @GajjarShalin Check these 2 posts about sending form data: http://stackoverflow.com/questions/793755/how-to-fill-forms-and-submit-with-webclient-in-c-sharp ... http://stackoverflow.com/questions/5401501/how-to-post-data-to-specific-url-using-webclient-in-c-sharp – Asons Jan 11 '16 at 09:07