Click here to Skip to main content
15,893,266 members
Articles / Web Development / ASP.NET

Download of file with open/save dialog box

Rate me:
Please Sign up or sign in to vote.
5.00/5 (18 votes)
1 Oct 2013CPOL4 min read 89K   5.1K   23  
In this article I will explain how to automate the process of downloading files with the open/save dialog box, protected by authentication.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

using System.Windows.Forms;

namespace WindowsFormsApplicationDW
{
    public partial class Form1 : Form
    {
        
        string sWebPath = "http://www.miosito.it/"; //change this path with WebApplicationTest's virtual path
        string sLocalPath = @"c:\"; //change this path, physical path of a file downloading  (write permission)
        string sMyName = "erika";
        string sPageLogin = "login.aspx";
        string sPageDw = "dw.aspx";
        bool bFirstTime;
        StreamWriter swWriterL;

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref uint pcchCookieData, int dwFlags, IntPtr lpReserved);
        
        const int INTERNET_COOKIE_HTTPONLY = 0x00002000;  
        
        private string GetGlobalCookies(string uri)
        {
            uint uiDataSize = 2048;
            StringBuilder sbCookieData = new StringBuilder((int)uiDataSize);
            if (InternetGetCookieEx(uri, null, sbCookieData, ref uiDataSize, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero) && sbCookieData.Length > 0)
            {
                return sbCookieData.ToString().Replace(";", ",");
            }
            else
            {
                return null;
            }
        }

        public Form1()
        {
            InitializeComponent();
            bFirstTime = true;
            timer1.Start(); // Then I start timer
            swWriterL = new StreamWriter(System.AppDomain.CurrentDomain.BaseDirectory + "log.log", true); // Inizializate log
            swWriterL.WriteLine("---------------------------------");
            swWriterL.WriteLine("Start working session " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
            webBrowser1.Navigate(sWebPath + sPageLogin);
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            swWriterL.WriteLine("Error timeout application");
            swWriterL.Close();
            timer1.Stop();
            this.Close();
            Application.Exit();

        }
        //extract __VIEWSTATE __EVENTVALIDATION from input type hidden
        private string ExtractInputHidden(string str, string name)
        {
            string sRit = "";
            string sPattern = "(?<=" + name  + "\" value=\")(?<val>.*?)(?=\")";
            Match match = Regex.Match(str, sPattern);
            if (match.Success)
            {
                sRit = match.Groups["val"].Value;
                sRit = HttpUtility.UrlEncodeUnicode(sRit);
            }
            return sRit;
        }
        
        
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
          //login page
            if ((bFirstTime == true) && (e.Url.ToString().Contains(sPageLogin))) //only first time
           {
                bFirstTime = false;
                HtmlElement heElement;
                heElement = (HtmlElement)webBrowser1.Document.GetElementById("UserEmail");
                heElement.InnerText = "name";
                heElement = (HtmlElement)webBrowser1.Document.GetElementById("UserPass");
                heElement.InnerText = "pass";
                System.Threading.Thread.Sleep(2000);
                heElement = (HtmlElement)webBrowser1.Document.GetElementById("Submit1");
                heElement.InvokeMember("click");
                System.Threading.Thread.Sleep(2000);
                webBrowser1.Navigate(sWebPath + sPageDw);
            }
            else
                if (e.Url.ToString().Contains(sPageDw) == true)
                {
                    try
                    {
                        //first request to extract __VIEWSTATE and __EVENTVALIDATION and cookie use get
                
                        string sPageData;
                        string PathRemote = sWebPath + sPageDw;
                        string sTmpCookieString =  GetGlobalCookies(webBrowser1.Url.AbsoluteUri);
                        HttpWebRequest fstRequest = (HttpWebRequest)WebRequest.Create(PathRemote);
                        fstRequest.Method = "GET";
                        fstRequest.CookieContainer = new System.Net.CookieContainer();
                        fstRequest.CookieContainer.SetCookies(webBrowser1.Document.Url, sTmpCookieString);
                        HttpWebResponse fstResponse = (HttpWebResponse)fstRequest.GetResponse();
                        StreamReader sr = new StreamReader(fstResponse.GetResponseStream());
                        sPageData = sr.ReadToEnd();
                        sr.Close();

                        string sViewState = ExtractInputHidden(sPageData, "__VIEWSTATE");
                        string sEventValidation = this.ExtractInputHidden(sPageData, "__EVENTVALIDATION");
                        
                        //second request post all values and save generated file
                        string sUrl = sWebPath + sPageDw;
                        HttpWebRequest hwrRequest = (HttpWebRequest)WebRequest.Create(sUrl);
                        hwrRequest.Method = "POST";
                        hwrRequest.CookieContainer = new System.Net.CookieContainer();

                        string sPostData = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=" + sViewState + "&__EVENTVALIDATION=" + sEventValidation + "&Name=" + sMyName + "&Button1=Button";

                        byte[] bByteArray = Encoding.UTF8.GetBytes(sPostData);
                        hwrRequest.ContentType = "application/x-www-form-urlencoded";
                        hwrRequest.CookieContainer.SetCookies(webBrowser1.Document.Url, sTmpCookieString);
                        hwrRequest.ContentLength = bByteArray.Length;
                        Stream sDataStream = hwrRequest.GetRequestStream();
                        sDataStream.Write(bByteArray, 0, bByteArray.Length);
                        sDataStream.Close();
                        using (WebResponse response = hwrRequest.GetResponse())
                        {
                            using (sDataStream = response.GetResponseStream())
                            {
                                StreamReader reader = new StreamReader(sDataStream);
                                {
                                    //get original file name
                                    string sHeader = response.Headers["Content-Disposition"];
                                    int iFileNameStartIndex = sHeader.IndexOf("filename=") + "filename=".ToString().Length;
                                    int iFileNameLength = sHeader.Length - iFileNameStartIndex;
                                    string sFileName = sHeader.Substring(iFileNameStartIndex, iFileNameLength); 
                                    string sResponseFromServer = reader.ReadToEnd();
                                    //save the file
                                    FileStream fs = File.Open(sLocalPath + sFileName, FileMode.OpenOrCreate, FileAccess.Write);
                                    Byte[] info = new System.Text.UTF8Encoding(true).GetBytes(sResponseFromServer);
                                    fs.Write(info, 0, info.Length);
                                    fs.Close();

                                    swWriterL.WriteLine("saved");
                                    reader.Close();
                                    sDataStream.Close();
                                    response.Close();
                                } //end StreamReader
                            } //end dataStream
                        }//end WebResponse
                    }//end try
                    catch (Exception eccezione)
                    {
                        swWriterL.WriteLine("Error: " + eccezione.Message);
                        swWriterL.Close();
                    }
                    swWriterL.Close();
                    this.Close(); //close form
                    Application.Exit();  //close app
                }
            }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer E-Group s.r.l.
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions