locked
Problem with HttpWebRequest RRS feed

  • Question

  • I have developed an application which is similar to Download Application Manager. I simply call that application with command line argument in which I pass the file location in webserver that has to be downloaded. I am using this code for that.

    private void DownloadMultiple()
    {
         try
         {
               {
                        StreamWriter w;
                        w = File.CreateText(filePath);
                        w.WriteLine("new file");
                        w.Flush();
                        w.Close();
                        
                        webRequest = (HttpWebRequest)WebRequest.Create(strURLPath);
                        // Set default authentication for retrieving the file
                        webRequest.Credentials = CredentialCache.DefaultCredentials;
                        // Retrieve the response from the server
                        webResponse = (HttpWebResponse)webRequest.GetResponse();
                        // Ask the server for the file size and store it
                        fileSize = webResponse.ContentLength;
    
                        // Open the URL for download 
                        strResponse = wcDownload.OpenRead(strURLPath);
                        // Create a new file stream where we will be saving the data (local drive)
    
                        strLocal = new FileStream(strfileName, FileMode.Create, FileAccess.Write, FileShare.None);
    
                        // It will store the current number of bytes we retrieved from the server
                        int bytesSize = 0;
                        // A buffer for storing and writing the data retrieved from the server
                        byte[] downBuffer = new byte[2048];
                        // Loop through the buffer until the buffer is empty
                        while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                        {
                            // Write the data from the buffer to the local hard drive
                            strLocal.Write(downBuffer, 0, bytesSize);
                            // Invoke the method that updates the form's label and progress bar
                            if (!bflag)
                                this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
                        }
                        //MessageBox.Show("download file completed");
    
                        System.Diagnostics.Process VxPlayer = new Process();
    
                        VxPlayer.StartInfo.FileName = "VxWebPlayer";
                        VxPlayer.StartInfo.Arguments = strfileName;
                        VxPlayer.StartInfo.CreateNoWindow = false;
    
                        VxPlayer.Start();
                        System.Windows.Forms.Application.Exit();
                        FileInfo TheFile = new FileInfo(filePath);
                        if (TheFile.Exists)
                        {
                            File.Delete(appPath + @"\" + strFileCheck[0] + ".tmp");
                   }
               }
           }
           catch (Exception ex)
           {
                //MessageBox.Show("The download has beed cancelled.");
           }
    }

    But there is a problem. When I pass this path in strURLPath.

    http://209.92.137.23/WindowsVista/ZentinelPlayer.msi

    It works. But when I pass this path with strURLPath

    http://209.92.137.23/Secure/VxPlayerVideos/5465_05162012_2423_AM.vvf

    It does'nt work. Although this URL Path does exist. How can I resolve this problem? Do i have to add this .vvf extension in IIS Server's MIME list? or is it sometihng else?


    Adeel

    Wednesday, May 9, 2012 10:39 AM

Answers

  • I think I got it almost working, here's the relevant code updated:

                    string loginHtml;
                    using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                        loginHtml = reader.ReadToEnd();
                    // we better extract the view state and event validation from html to post it back, it might not work without these
                    string viewStateField = "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"";
                    int viewStateStart = loginHtml.IndexOf(viewStateField) + viewStateField.Length;
                    int viewStateEnd = loginHtml.IndexOf('"', viewStateStart);
                    string viewState = System.Web.HttpUtility.HtmlDecode(loginHtml.Substring(viewStateStart, viewStateEnd - viewStateStart));
                    string validationField = "<input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"";
                    int validationStart = loginHtml.IndexOf(validationField) + validationField.Length;
                    int validationEnd = loginHtml.IndexOf('"', validationStart);
                    string validation = System.Web.HttpUtility.HtmlDecode(loginHtml.Substring(validationStart, validationEnd - validationStart));
                    response.Close();
                    request = (HttpWebRequest)WebRequest.Create(loginUrl);
                    request.CookieContainer = cookies;
                    request.AllowAutoRedirect = true;
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded"; // I forgot this, it's important for a POST
                    
                    using (Stream stream = request.GetRequestStream())
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        // modified this to send all fields that are normally sent by the login page
                        // also added proper encoding
                        writer.Write(
                            "ScriptManager1_HiddenField=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={0}&__EVENTVALIDATION={1}&UserName={2}&Password={3}&LoginButton.x=48&LoginButton.y=14", 
                            System.Web.HttpUtility.UrlEncode(viewState),
                            System.Web.HttpUtility.UrlEncode(validation),
                            System.Web.HttpUtility.UrlEncode("user"), 
                            System.Web.HttpUtility.UrlEncode("password"));
                    }
                    response = (HttpWebResponse)request.GetResponse();

    The way it extracts the view state and validation is kind of brute force but it does the job at least for testing purposes.

    Now I say "almost" working because it appears that I got redirected to some /Secure/default.aspx page instead of being redirected to the ReturnURL. I'm not sure why it does that, might be a problem with the way the site handles the login.

    You may want to use Fiddler (http://fiddler2.com/fiddler2/) to take a look at the request this code makes.


    • Edited by Mike Danes Wednesday, May 9, 2012 4:49 PM
    • Proposed as answer by Mr. Javaman II Wednesday, May 9, 2012 11:21 PM
    • Marked as answer by maverick786us Thursday, May 10, 2012 6:29 AM
    Wednesday, May 9, 2012 4:49 PM
  • "Where?"

    Here:

      // Open the URL for download 
      strResponse = wcDownload.OpenRead(strURLPath);

    Use

    strResponse = webResponse.GetResponseStream();

    instead.

    • Proposed as answer by Mr. Javaman II Wednesday, May 9, 2012 11:21 PM
    • Marked as answer by maverick786us Thursday, May 10, 2012 6:30 AM
    Wednesday, May 9, 2012 5:34 PM

All replies

  • Which error or exception do you receive and where?

    Wednesday, May 9, 2012 10:57 AM
  • There is no error but. It only downloads 4KB of that file and in progressbar it shows as if it completely downloaded the file. In this section of code

    webRequest = (HttpWebRequest)WebRequest.Create(strURLPath);
    // Set default authentication for retrieving the file
    webRequest.Credentials = CredentialCache.DefaultCredentials;
    // Retrieve the response from the server
    webResponse = (HttpWebResponse)webRequest.GetResponse();
    // Ask the server for the file size and store it
    fileSize = webResponse.ContentLength;

    After getting the response the fileSize that it shows is just 4KB and in actual its almost 5 MB and it downloads only that much portion over here....

    while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { // Write the data from the buffer to the local hard drive strLocal.Write(downBuffer, 0, bytesSize); // Invoke the method that updates the form's label and progress bar if (!bflag) this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize }); }



    Adeel

    Wednesday, May 9, 2012 11:03 AM
  • If your second link requires login, then try assigning a NetworkCredential object to webRequest.Crtedentials, specifying username and password.

    Wednesday, May 9, 2012 12:45 PM
  • thanks so I will change my code to this.

    webRequest = (HttpWebRequest)WebRequest.Create(strURLPath);
    // Set default authentication for retrieving the file
    webRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
    // Retrieve the response from the server
    webResponse = (HttpWebResponse)webRequest.GetResponse();
    // Ask the server for the file size and store it
    fileSize = webResponse.ContentLength;
    Now how can I add the code for username and password? Although only when the user is logged in, then only he has access to this download

    Adeel


    Wednesday, May 9, 2012 12:51 PM
  • If you know the username and password, then try this:

        webRequest.Credentials = new NetworkCredential( username, password );

    Wednesday, May 9, 2012 1:03 PM
  • If you know the username and password, then try this:

        webRequest.Credentials = new NetworkCredential( username, password );

    Still didn't work :(

     {
                        StreamWriter w;
                        w = File.CreateText(filePath);
                        w.WriteLine("new file");
                        w.Flush();
                        w.Close();
                        
                        webRequest = (HttpWebRequest)WebRequest.Create(strURLPath);
                        // Set default authentication for retrieving the file
                        webRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
                        webRequest.Credentials = new NetworkCredential("username", "password");
                        // Retrieve the response from the server
                        webResponse = (HttpWebResponse)webRequest.GetResponse();
                        // Ask the server for the file size and store it
                        fileSize = webResponse.ContentLength;
    
                        // Open the URL for download 
                        strResponse = wcDownload.OpenRead(strURLPath);
                        // Create a new file stream where we will be saving the data (local drive)
    
                        strLocal = new FileStream(strfileName, FileMode.Create, FileAccess.Write, FileShare.None);
    
                        // It will store the current number of bytes we retrieved from the server
                        int bytesSize = 0;
                        // A buffer for storing and writing the data retrieved from the server
                        byte[] downBuffer = new byte[2048];
                        // Loop through the buffer until the buffer is empty
                        while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
                        {
                            // Write the data from the buffer to the local hard drive
                            strLocal.Write(downBuffer, 0, bytesSize);
                            // Invoke the method that updates the form's label and progress bar
                            if (!bflag)
                                this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
                        }
                        //MessageBox.Show("download file completed");
    
                        System.Diagnostics.Process VxPlayer = new Process();
    
                        VxPlayer.StartInfo.FileName = "VxWebPlayer";
                        VxPlayer.StartInfo.Arguments = strfileName;
                        VxPlayer.StartInfo.CreateNoWindow = false;
    
                        VxPlayer.Start();
                        System.Windows.Forms.Application.Exit();
                        FileInfo TheFile = new FileInfo(filePath);
                        if (TheFile.Exists)
                        {
                            File.Delete(appPath + @"\" + strFileCheck[0] + ".tmp");
                        }
                    }


    Adeel


    Wednesday, May 9, 2012 1:31 PM
  • Run a communications trace using Wireshark and see what is happening at packet layer.  Everything so far, has been guesswork.

    JP Cowboy Coders Unite!

    Wednesday, May 9, 2012 1:34 PM
  • How does Wireshark works? Will adding Proxy help?

    Adeel

    Wednesday, May 9, 2012 2:00 PM
  • That web page appears to use Forms authentication, that won't work with credentials.

    If you try it in browser then you'll see that it really does a redirect to a login page. That's likely to be complicated to deal with when using HttpWebRequest, you'll have to try to extract from the html page the names of the user and password fields, make another POST request with the actual user and password and finally go back to the original url and try to download.

    Wednesday, May 9, 2012 2:04 PM
  • That web page appears to use Forms authentication, that won't work with credentials.

    If you try it in browser then you'll see that it really does a redirect to a login page. That's likely to be complicated to deal with when using HttpWebRequest, you'll have to try to extract from the html page the names of the user and password fields, make another POST request with the actual user and password and finally go back to the original url and try to download.


    Can you demonstrate this with source code? I do have the actual username and password.

    Adeel

    Wednesday, May 9, 2012 2:13 PM
  • "Can you demonstrate this with source code?"

    That's not exactly trivial, normally it requires you to parse the returned html to extract input field names. Do you have any form of control on that page to know that these names won't change?

    Wednesday, May 9, 2012 2:43 PM
  • "Can you demonstrate this with source code?"

    That's not exactly trivial, normally it requires you to parse the returned html to extract input field names. Do you have any form of control on that page to know that these names won't change?


    they wont change: field names:
    TextBox ID="UserName"
    TextBox ID="Password"

    Adeel

    Wednesday, May 9, 2012 2:58 PM
  • Something like this:

                Uri url = new Uri("http://209.92.137.23/Secure/VxPlayerVideos/5465_05162012_2423_AM.vvf");
                CookieContainer cookies = new CookieContainer(); // Forms auth requires cookies
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.CookieContainer = cookies;
                request.AllowAutoRedirect = false; // disable auto redirect so we know when to login
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.Redirect) {
                    string newLocation = response.Headers[HttpResponseHeader.Location];
                    response.Close();
                    Uri loginUrl = new Uri(url, newLocation); // this is the login page url
                    request = (HttpWebRequest)WebRequest.Create(loginUrl);
                    request.CookieContainer = cookies;
                    response = (HttpWebResponse)request.GetResponse();
                    string loginHtml;
                    using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                        loginHtml = reader.ReadToEnd(); // get the login page html, we may need it later
                    response.Close();
                    request = (HttpWebRequest)WebRequest.Create(loginUrl);
                    request.CookieContainer = cookies;
                    request.Method = "POST"; // make a POST to the login url with valid username and password
                    
                    using (Stream stream = request.GetRequestStream())
                    using (StreamWriter writer = new StreamWriter(stream)) {
                        writer.Write("UserName={0}&Password={1}", "foo", "bar");
                    }
                    response = (HttpWebResponse)request.GetResponse(); // if everything works fine now this should contain the file we want
                }
    But I suspect you will get a error from the server if you try it with a valid user name and password. The problem is that you may still need to extract some field values (__VIEWSTATE and __EVENTVALIDATION) from html and post them back.
    Wednesday, May 9, 2012 3:23 PM
  • You were right. The result is still the same. This is the final code :(

    try { { StreamWriter w; w = File.CreateText(filePath); w.WriteLine("new file"); w.Flush(); w.Close(); Uri url= new Uri(strURLPath);

    // Forms auth requires cookies CookieContainer cookies = new CookieContainer(); webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.CookieContainer = cookies; // disable auto redirect so we know when to login webRequest.AllowAutoRedirect = false; webResponse = (HttpWebResponse)webRequest.GetResponse(); if (webResponse.StatusCode == HttpStatusCode.Redirect) { string strNewLocation = webResponse.Headers[HttpResponseHeader.Location]; webResponse.Close(); // this is the login page url Uri loginUrl = new Uri(url, strNewLocation); webRequest = (HttpWebRequest)WebRequest.Create(loginUrl); webRequest.CookieContainer = cookies; webResponse = (HttpWebResponse)webRequest.GetResponse(); string strLoginHtml; using (Stream stream = webResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) // get the login page html, we may need it later strLoginHtml = reader.ReadToEnd(); } webResponse.Close(); webRequest = (HttpWebRequest)WebRequest.Create(loginUrl); webRequest.CookieContainer = cookies; // make a POST to the login url with valid username and password webRequest.Method = "POST"; using (Stream stream = webRequest.GetRequestStream()) { using (StreamWriter writer = new StreamWriter(stream)) { writer.Write("UserName={0}&Password={1}", "username", "password"); } } } // if everything works fine now this should contain the file we want webResponse = (HttpWebResponse)webRequest.GetResponse(); // Ask the server for the file size and store it fileSize = webResponse.ContentLength; // Open the URL for download strResponse = wcDownload.OpenRead(strURLPath); // Create a new file stream where we will be saving the data (local drive) strLocal = new FileStream(strfileName, FileMode.Create, FileAccess.Write, FileShare.None); // It will store the current number of bytes we retrieved from the server int bytesSize = 0; // A buffer for storing and writing the data retrieved from the server byte[] downBuffer = new byte[2048]; // Loop through the buffer until the buffer is empty while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { // Write the data from the buffer to the local hard drive strLocal.Write(downBuffer, 0, bytesSize); // Invoke the method that updates the form's label and progress bar if (!bflag) this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize }); } System.Diagnostics.Process VxPlayer = new Process(); VxPlayer.StartInfo.FileName = "VxWebPlayer"; VxPlayer.StartInfo.Arguments = strfileName; VxPlayer.StartInfo.CreateNoWindow = false; VxPlayer.Start(); System.Windows.Forms.Application.Exit(); FileInfo TheFile = new FileInfo(filePath); if (TheFile.Exists) { File.Delete(appPath + @"\" + strFileCheck[0] + ".tmp"); } } } catch (Exception ex) { //MessageBox.Show("The download has beed cancelled."); }



    Adeel


    Wednesday, May 9, 2012 4:11 PM
  • I'll take a look in a moment but until then you may want to remove the user and password from your posted code :)
    Wednesday, May 9, 2012 4:18 PM
  • I'll take a look in a moment but until then you may want to remove the user and password from your posted code :)

    Thank you for the advice. I can even provide you the whole source code if you want. You can get it here. With the name of DownloadManagerProject

    Adeel



    Wednesday, May 9, 2012 4:27 PM
  • I think I got it almost working, here's the relevant code updated:

                    string loginHtml;
                    using (Stream stream = response.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                        loginHtml = reader.ReadToEnd();
                    // we better extract the view state and event validation from html to post it back, it might not work without these
                    string viewStateField = "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"";
                    int viewStateStart = loginHtml.IndexOf(viewStateField) + viewStateField.Length;
                    int viewStateEnd = loginHtml.IndexOf('"', viewStateStart);
                    string viewState = System.Web.HttpUtility.HtmlDecode(loginHtml.Substring(viewStateStart, viewStateEnd - viewStateStart));
                    string validationField = "<input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\"";
                    int validationStart = loginHtml.IndexOf(validationField) + validationField.Length;
                    int validationEnd = loginHtml.IndexOf('"', validationStart);
                    string validation = System.Web.HttpUtility.HtmlDecode(loginHtml.Substring(validationStart, validationEnd - validationStart));
                    response.Close();
                    request = (HttpWebRequest)WebRequest.Create(loginUrl);
                    request.CookieContainer = cookies;
                    request.AllowAutoRedirect = true;
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded"; // I forgot this, it's important for a POST
                    
                    using (Stream stream = request.GetRequestStream())
                    using (StreamWriter writer = new StreamWriter(stream))
                    {
                        // modified this to send all fields that are normally sent by the login page
                        // also added proper encoding
                        writer.Write(
                            "ScriptManager1_HiddenField=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={0}&__EVENTVALIDATION={1}&UserName={2}&Password={3}&LoginButton.x=48&LoginButton.y=14", 
                            System.Web.HttpUtility.UrlEncode(viewState),
                            System.Web.HttpUtility.UrlEncode(validation),
                            System.Web.HttpUtility.UrlEncode("user"), 
                            System.Web.HttpUtility.UrlEncode("password"));
                    }
                    response = (HttpWebResponse)request.GetResponse();

    The way it extracts the view state and validation is kind of brute force but it does the job at least for testing purposes.

    Now I say "almost" working because it appears that I got redirected to some /Secure/default.aspx page instead of being redirected to the ReturnURL. I'm not sure why it does that, might be a problem with the way the site handles the login.

    You may want to use Fiddler (http://fiddler2.com/fiddler2/) to take a look at the request this code makes.


    • Edited by Mike Danes Wednesday, May 9, 2012 4:49 PM
    • Proposed as answer by Mr. Javaman II Wednesday, May 9, 2012 11:21 PM
    • Marked as answer by maverick786us Thursday, May 10, 2012 6:29 AM
    Wednesday, May 9, 2012 4:49 PM
  • This is what Fiddler shows.

    http://209.92.137.23/Secure/VxPlayerVideos/9876_05092012_1234_AM.msi
    http://209.92.137.23/login.aspx?ReturnUrl=%2fSecure%2fVxPlayerVideos%2f9876_05092012_1234_AM.msi
    http://209.92.137.23/login.aspx?ReturnUrl=%2fSecure%2fVxPlayerVideos%2f9876_05092012_1234_AM.msi
    http://209.92.137.23/Secure/VxPlayerVideos/9876_05092012_1234_AM.msi
    http://209.92.137.23/login.aspx?ReturnUrl=%2fSecure%2fVxPlayerVideos%2f9876_05092012_1234_AM.msi

    In my case it does'nt redirect Default.aspx but to the MSI file and yet the result is still the same :( Here is my final source code

    { //StreamWriter w; //w = File.CreateText(filePath); //w.WriteLine("new file"); //w.Flush(); //w.Close(); Uri url= new Uri(strURLPath); //NetworkCredential myCredentials = new NetworkCredential("", "", ""); //myCredentials.Domain = "http://209.92.137.23/login.aspx"; //myCredentials.UserName = "maverick786us"; //myCredentials.Password = "plmokn33#"; // Forms auth requires cookies CookieContainer cookies = new CookieContainer(); webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.CookieContainer = cookies; // disable auto redirect so we know when to login webRequest.AllowAutoRedirect = false; // Set default authentication for retrieving the file //webRequest.Credentials = CredentialCache.DefaultNetworkCredentials; //webRequest.Credentials = myCredentials; // Retrieve the response from the server webResponse = (HttpWebResponse)webRequest.GetResponse(); if (webResponse.StatusCode == HttpStatusCode.Redirect) { string strNewLocation = webResponse.Headers[HttpResponseHeader.Location]; webResponse.Close(); // this is the login page url Uri loginUrl = new Uri(url, strNewLocation); webRequest = (HttpWebRequest)WebRequest.Create(loginUrl); webRequest.CookieContainer = cookies; webResponse = (HttpWebResponse)webRequest.GetResponse(); string strLoginHtml; using (Stream stream = webResponse.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream)) // get the login page html, we may need it later strLoginHtml = reader.ReadToEnd(); } // we better extract the view state and event validation from html to post it back, it might not work without these string viewStateField = "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\""; int viewStateStart = strLoginHtml.IndexOf(viewStateField) + viewStateField.Length; int viewStateEnd = strLoginHtml.IndexOf('"', viewStateStart); string viewState = System.Web.HttpUtility.HtmlDecode(strLoginHtml.Substring(viewStateStart, viewStateEnd - viewStateStart)); string validationField = "<input type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\" value=\""; int validationStart = strLoginHtml.IndexOf(validationField) + validationField.Length; int validationEnd = strLoginHtml.IndexOf('"', validationStart); string validation = System.Web.HttpUtility.HtmlDecode(strLoginHtml.Substring(validationStart, validationEnd - validationStart)); webResponse.Close(); webRequest = (HttpWebRequest)WebRequest.Create(loginUrl); webRequest.CookieContainer = cookies;

    webRequest.AllowAutoRedirect =

    true;

                           

    // make a POST to the login url with valid username and password


                            webRequest.Method =

                            webRequest.ContentType =

    "application/x-www-form-urlencoded"; // I forgot this, it's important for a POST

    // make a POST to the login url with valid username and password webRequest.Method = "POST"; using (Stream stream = webRequest.GetRequestStream()) { using (StreamWriter writer = new StreamWriter(stream)) { // modified this to send all fields that are normally sent by the login page // also added proper encoding writer.Write( "ScriptManager1_HiddenField=&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={0}&__EVENTVALIDATION={1}&UserName={2}&Password={3}&LoginButton.x=48&LoginButton.y=14", System.Web.HttpUtility.UrlEncode(viewState), System.Web.HttpUtility.UrlEncode(validation), System.Web.HttpUtility.UrlEncode("username"), System.Web.HttpUtility.UrlEncode("password")); } } } // if everything works fine now this should contain the file we want webResponse = (HttpWebResponse)webRequest.GetResponse(); // Ask the server for the file size and store it fileSize = webResponse.ContentLength; // Open the URL for download strResponse = wcDownload.OpenRead(strURLPath); // Create a new file stream where we will be saving the data (local drive) strLocal = new FileStream(strfileName, FileMode.Create, FileAccess.Write, FileShare.None); // It will store the current number of bytes we retrieved from the server int bytesSize = 0; // A buffer for storing and writing the data retrieved from the server byte[] downBuffer = new byte[2048]; // Loop through the buffer until the buffer is empty while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0) { // Write the data from the buffer to the local hard drive strLocal.Write(downBuffer, 0, bytesSize); // Invoke the method that updates the form's label and progress bar if (!bflag) this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize }); } System.Diagnostics.Process VxPlayer = new Process(); VxPlayer.StartInfo.FileName = "VxWebPlayer"; VxPlayer.StartInfo.Arguments = strfileName; VxPlayer.StartInfo.CreateNoWindow = false; VxPlayer.Start(); System.Windows.Forms.Application.Exit(); FileInfo TheFile = new FileInfo(filePath); if (TheFile.Exists) { File.Delete(appPath + @"\" + strFileCheck[0] + ".tmp"); } }

    POST";


    Adeel


    Wednesday, May 9, 2012 5:11 PM
  • Hmm, there's something I forgot to ask about your original code. What's with wcDownload.OpenRead? Is that a WebClient object?

    If so, don't use that, use the stream returned by webResponse.GetResponseStream.

    • Proposed as answer by Mr. Javaman II Wednesday, May 9, 2012 11:21 PM
    Wednesday, May 9, 2012 5:16 PM
  • the only difference is the amount of data stored in filesize is 58KB this time. previously it was only 4 KBs

    // Ask the server for the file size and store it
    fileSize = webResponse.ContentLength;


    Adeel

    Wednesday, May 9, 2012 5:19 PM
  • Then check what content did you receive, obviously something changed. Maybe you got redirected to that default.aspx page like me.

    • Proposed as answer by Mr. Javaman II Wednesday, May 9, 2012 11:21 PM
    Wednesday, May 9, 2012 5:24 PM
  • Hmm, there's something I forgot to ask about your original code. What's with wcDownload.OpenRead? Is that a WebClient object?

    If so, don't use that, use the stream returned by webResponse.GetResponseStream.


    Where?

    Adeel

    Wednesday, May 9, 2012 5:29 PM
  • "Where?"

    Here:

      // Open the URL for download 
      strResponse = wcDownload.OpenRead(strURLPath);

    Use

    strResponse = webResponse.GetResponseStream();

    instead.

    • Proposed as answer by Mr. Javaman II Wednesday, May 9, 2012 11:21 PM
    • Marked as answer by maverick786us Thursday, May 10, 2012 6:30 AM
    Wednesday, May 9, 2012 5:34 PM
  • Thanks for all the help that you've provided. I have asked the developer to make changes with the website so that it does'nt redirect into default.aspx. Its 11:00 Night here so I will try this again once the site is modified.

    Adeel

    Wednesday, May 9, 2012 5:39 PM