如何讓程序自動更新

        自動更新的軟件的目的在於讓客戶不在爲了尋找最新軟件花費時間。也不用去到開發商的網站上查找。客戶端的軟件自動會在程序啓動前查找服務器上最新的版本。和本身當前軟件的版本比較,若是服務器的是最新版本。客戶端則進行自動下載、解壓、安裝。固然了下載是要有網絡的,而且用戶能夠根據提示去完成操做。不再用爲找不到最新版本的軟件而頭疼。下面是個人大致思路,已經獲得了實現:web

       一、  寫一個webservice,提供一個獲取服務器xml中版本的數據的方法。(也可用其餘文件格式, 此處舉例XML)服務器

       二、  在WinForm應用程序啓動的時候,首先訪問webservice獲取服務器的xml中的版本號,而後獲取客戶端的xml中的版本號。將兩個版本號比較,若服務器中的版本號大,則提示提示能夠在線更新應用程序。網絡

       三、  而後客戶端自動下載網絡上的RAR壓縮包到本機的指定位置,進行自動解壓縮。解壓縮完畢以後,用進程打開所解壓過的exe文件進行軟件安裝。同時關閉客戶端軟件所在的進程。ide

  一   web項目中的代碼網站

       首先我給你們先展現下個人web項目中的webservice的代碼,這裏面跟簡單,只有一個方法。項目須要發佈到IIS上面。this

     1.1 webservice中的代碼spa

          

 [STAThread]

        static void Main()

        {

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            LoadMath();

        }

        private static void LoadMath()

        {

            //服務器上的版本號

            string NewEdition = string.Empty;

            //應用程序中的版本號

            string OldEdition = string.Empty;

            try

            {

                //獲取webservice上的版本號

                myService.WebServiceUpdateSoapClient c = new myService.WebServiceUpdateSoapClient();

                NewEdition = c.GetEdition("clkj_ws");

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            try

            {

                //獲取系統中xml裏面存儲的版本號

                XDocument document = XDocument.Load("XMLEdition.xml");

                XElement element = document.XPathSelectElement("Content/Project/Edition");

                if (element != null)

                {

                    OldEdition = element.Value.ToString();

                }

            }

            catch (Exception exx)

            {

                MessageBox.Show(exx.Message);

            }

            double newE = double.Parse(NewEdition);

            double oldE = double.Parse(OldEdition);

            //比較兩個版本號,判斷應用程序是否要更新

            if (newE > oldE)

            {

               

                //更新程序¨°

                DialogResult dr = MessageBox.Show("發現新的版本是否要更新該軟件", "系統提示?", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

                if (dr == DialogResult.OK)

                {

                    //打開下載窗口

                    Application.Run(new DownUpdate ());

                }

                else

                {

                    //若用戶取消,打開初始界面

                    Application.Run(new Login());

                }

            }

        }
View Code

 

  1.2 xml中的代碼debug

      

<?xml version="1.0" encoding="utf-8" ?>code

<Content>orm

  <Project id="p1">

    <Name>test</Name>

    <Edition>2.0</Edition>

  </Project>

</Content>  

二   WinForm項目中的代碼

      Web項目的代碼就只有上面的一點,重點的仍是在WinForm中。在WinForm中首先要添加web引用,將上述的webservice訪問地址複製過來使用。下面我一步一步來爲你們解析吧。

   第一步:

     2.1 xml中的代碼

    客戶端的代碼和服務器斷的xml代碼大體相同,不一樣的只用Edition元素裏面的值。

    <?xml version="1.0" encoding="utf-8" ?>

      <Content>

        <Project id="p1">

          <Name>test</Name>

          <Edition>1.0</Edition>

         </Project>

      </Content>

2.2 Program.cs代碼(設置起始頁的代碼)

在Program.cs(WinForm中設置起始頁的地方)這個類中添加代碼

 

 [STAThread]

        static void Main()

        {

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);

            LoadMath();

        }

        private static void LoadMath()

        {

            //服務器上的版本號

            string NewEdition = string.Empty;

            //應用程序中的版本號

            string OldEdition = string.Empty;

            try

            {

                //獲取webservice上的版本號

                myService.WebServiceUpdateSoapClient c = new myService.WebServiceUpdateSoapClient();

                NewEdition = c.GetEdition("clkj_ws");

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            try

            {

                //獲取系統中xml裏面存儲的版本號

                XDocument document = XDocument.Load("XMLEdition.xml");

                XElement element = document.XPathSelectElement("Content/Project/Edition");

                if (element != null)

                {

                    OldEdition = element.Value.ToString();

                }

            }

            catch (Exception exx)

            {

                MessageBox.Show(exx.Message);

            }

            double newE = double.Parse(NewEdition);

            double oldE = double.Parse(OldEdition);

            //比較兩個版本號,判斷應用程序是否要更新

            if (newE > oldE)

            {

               

                //更新程序¨°

                DialogResult dr = MessageBox.Show("發現新的版本是否要更新該軟件", "系統提示?", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

                if (dr == DialogResult.OK)

                {

                    //打開下載窗口

                    Application.Run(new DownUpdate ());

                }

                else

                {

                    //若用戶取消,打開初始界面

                    Application.Run(new Login());

                }

            }

        }

 

    2.3 Main.cs(登陸後的主界面)的代碼

           這個能夠省略,沒有實際意義

    2.4 DownUpdate.cs(更新頁面)的代碼

      界面顯示以下圖

                  

自動更新代碼以下(其中更新按鈕的name爲btnDown,安裝按鈕的name爲btnInstall):

  

//debug目錄,用於存放壓縮文件t
        string path = Application.StartupPath;
        public DownExe()
        {
            InitializeComponent();
        }

        private void DownExe_Load(object sender, EventArgs e)
        {
            btnInstall.Enabled = false;
        }

        //下載文件、自動解壓縮文件
        private void btnDown_Click(object sender, EventArgs e)
        {
            //自動下載壓縮包,而且解壓,最後關閉當前進程,進行安裝
            try
            {
                //設置進度條
                List<int> resultList = new List<int>();
                for (int i = 0; i < 100; i++)
                {
                    resultList.Add(i);
                }

                //設置進度條的最大值和最小值
                this.progressBar1.Maximum = resultList.Count;
                this.progressBar1.Minimum = 0;

                foreach (int item in resultList)
                {
                    //下載壓縮包
                    System.Net.WebClient client = new System.Net.WebClient();
                    client.DownloadFile(@"http://192.168.1.120/File/setup.rar", path + @"setup.rar");
                    this.progressBar1.Value++;
                }
            }
            catch
            {
                MessageBox.Show("當前沒有網絡或者文件地址不正確");
            }

            if (!Exists())
            {
                MessageBox.Show("不支持RAR解壓縮");
                return;
            }
            //解a壓1
            try
            {
                unCompressRAR(path + "\\setup", path, "setup.rar", false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            btnInstall.Enabled = true;
            btnDown.Enabled = false;
        }

        //打開下載好的exe文件,而且關閉當前客戶端所在的進程
        private void btnInstall_Click(object sender, EventArgs e)
        {
            if (File.Exists(path + @"\setup\cboxbeta2.0.0.7.exe"))
            {
                //打開下載好的exe文件
                Process.Start(path + @"\setup\cboxbeta2.0.0.7.exe");
                //關閉當前進程
                Process[] proce = Process.GetProcesses();
                foreach (Process p in proce)
                {
                    //當前運行軟件的進程名字
                    if (p.ProcessName == "TestAutoUpdate.vshost")
                    {
                        p.Kill();
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 解壓縮文件t
        /// </summary>
        /// <param name="unRarPatch">解壓縮後的文件所要存放的路徑?</param>
        /// <param name="rarPatch">rar文件所在的路徑</param>
        /// <param name="rarName">rar文件名</param>
        /// <param name="deleteFlag"></param>
        /// <returns></returns>
        public static string unCompressRAR(string unRarPatch, string rarPatch, string rarName, bool deleteFlag)
        {
            try
            {
              
                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
                string str = key.GetValue("").ToString();
                key.Close();
                if (!System.IO.Directory.Exists(unRarPatch))
                {
                    System.IO.Directory.CreateDirectory(unRarPatch);
                }
                string str2 = "x \"" + rarName + "\" \"" + unRarPatch+"\""+" -y";
                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = str;
                info.Arguments = str2;
                info.WindowStyle = ProcessWindowStyle.Hidden;
                info.WorkingDirectory = rarPatch;
                Process process = new Process();
                process.StartInfo = info;
                process.Start();
                process.WaitForExit();
                process.Close();
                if (deleteFlag && System.IO.File.Exists(rarPatch + @"\" + rarName))
                {
                    System.IO.File.Delete(rarPatch + @"\" + rarName);
                }
            }
            catch (Exception exception)
            {
                throw exception;
            }
            return unRarPatch;
        }

        /// <summary>
        /// 判讀是否支持RAR自動解壓縮
        /// </summary>
        /// <returns></returns>
        public static bool Exists()
        {
            return !string.IsNullOrEmpty(Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe").GetValue("").ToString());
        }
View Code
相關文章
相關標籤/搜索