C# 程序自動升級的源碼

把寫代碼過程重要的代碼段珍藏起來,如下的代碼內容是關於C# 程序自動升級的的代碼。

<?xml version="1.0" encoding="utf-8" ?>
<Content>
  <Project id="程序名稱" Edition="1.0"> </Project>
</Content>

2、在WinForm應用程序啓動的時候,首先訪問webservice獲取服務器的xml中的版本號,然後獲取客戶端的xml中的版本號。將兩個版本號比較,若服務器中的版本號大,則提示提示可以在線更新應用程序。3、然後客戶端自動下載網絡上的zip壓縮包到本機的指定位置,進行自動解壓縮到安裝的目錄進行覆蓋。解壓縮完畢之後,用進程打開所解壓過的exe文件進行軟件安裝。同時關閉客戶端軟件所在的進程。4、注意:升級程序和應用程序都是單獨的,應用程序在使用時不能對本身進行升級(覆蓋會失敗)。具體代碼如下:第一部分應用程序如口Program:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Medicine_ERP;
using DevExpress.XtraEditors;
using System.Xml;
using Anshield_AutoFutures.BaseClase;

namespace Anshield_AutoFutures
{
    static class Program
    {
        private static void LoadMath()
        {
            string NewEdition = "1.0";
            string OldEdition = "1.0";

            try
            {
                NewEdition = webserverClase.getCopyRightCode();

                String fileName = Application.StartupPath + "\XMLEdition.xml";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fileName);
                XmlNode xn = xmlDoc.SelectSingleNode("Content");
                XmlNodeList xnl = xn.ChildNodes;
                foreach (XmlNode xnf in xnl)
                {
                    XmlElement xe = (XmlElement)xnf;
                    if (xe.GetAttribute("id") == "jigou_plz")
                    {
                    }
                    break;
                }
                double newE = double.Parse(NewEdition);
                double oldE = double.Parse(OldEdition);
                if (newE > oldE)
                {
                    DialogResult dr = XtraMessageBox.Show("發現新的版本是否要更新該軟件", "平浪舟現貨程序化交易--更新提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                    if (dr == DialogResult.OK)
                    {

                        System.Diagnostics.Process.Start(Application.StartupPath + @"Upgrade_Form.exe");

                        Application.Exit();
                    }
                    else
                    {
                        anshield_Login login = new anshield_Login();
                        if (login.ShowDialog() == DialogResult.OK)
                        {
                            Application.Run(new Main_AutoFutures());
                        }
                    }
                }
                else
                {
                    anshield_Login login = new anshield_Login();
                    if (login.ShowDialog() == DialogResult.OK)
                    {
                        Application.Run(new Main_AutoFutures());
                    }
                }
            }
            catch
            {
                XtraMessageBox.Show("網絡鏈接失敗!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }

      
        [STAThread]
        static void Main()
        {
            
            System.Threading.Mutex mutexMyapplication = new System.Threading.Mutex(false, "jigou_plz.exe");
            if (!mutexMyapplication.WaitOne(100, false))
            {
                XtraMessageBox.Show("程序" + Application.ProductName + "已經在運行!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);              
                return;
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                hugengyong hu = new hugengyong();               
                DevExpress.UserSkins.OfficeSkins.Register();
                DevExpress.Skins.SkinManager.EnableFormSkins();
                DevExpress.UserSkins.BonusSkins.Register();

                LoadMath();
                }
        }
    }
}

第二部分:升級程序代碼如下:

        string path = Application.StartupPath;

 private void btnDown_Click(object sender, EventArgs e)
        {
            string zipFile = path + @"jigou_plz.zip";
            killProess();
            
            btnDown.Enabled = false;
            button2.Enabled = false;
            try
            {
                string downUrl = ConfigurationManager.ConnectionStrings["DownUrl"].ConnectionString.ToString().Trim();
                if (!string.IsNullOrEmpty(downUrl))
                {
                    DownloadFile(downUrl, zipFile, progressBar1, label1);
                }
                else
                {
                    MessageBox.Show("Config中的下載路徑配置錯誤!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            catch
            {
                MessageBox.Show("當前沒有網絡或者文件地址不正確");
                return;
            }          
            try
            {
                killProess();
                BaseClase.Zip.UnZip(zipFile, path, "", true,true);
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            if (MessageBox.Show("升級完成!,請重新登陸!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
            {
                if (file.Exists)
                {
                    Process.Start(path + @"Anshield_AutoFutures.exe");
                }             
                Application.Exit();
            }
           
        }
        public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            float percent = 0;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);

                    label1.Text = "下載進度" + percent.ToString() + "%";
                }
                label1.Text = "下載完成。安裝中... ...";
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }

 

        private void killProess()
        {
            this.label1.Text = "正在關閉程序....";
            System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("Anshield_AutoFutures");
            foreach (System.Diagnostics.Process pro in proc)
            {
                pro.Kill();
            }
        }

zip壓縮文件解壓方法類

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Compression;
using ICSharpCode.SharpZipLib.Zip;

namespace Upgrade_Form.BaseClase
{
    class Zip
    {
     
        public static void UnZip(string zipedFile, string strDirectory, string password, bool overWrite,bool delteFile)
        {
            if (Directory.Exists(strDirectory) == false)
            {
                Directory.CreateDirectory(strDirectory);
            }
            if (strDirectory == "")
                strDirectory = Directory.GetCurrentDirectory();
            if (!strDirectory.EndsWith("\"))
                strDirectory = strDirectory + "\";

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
            {
                s.Password = password;
                ZipEntry theEntry;

                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = "";
                    string pathToZip = "";
                    pathToZip = theEntry.Name;

                    if (pathToZip != "")
                        directoryName = Path.GetDirectoryName(pathToZip) + "\";

                    string fileName = Path.GetFileName(pathToZip);

                    Directory.CreateDirectory(strDirectory + directoryName);

                    if (fileName != "")
                    {
                        if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
                        {
                            using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
                            {
                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
size = s.Read(data, 0, data.Length);

if (size > 0)
    streamWriter.Write(data, 0, size);
else
    break;
                                }
                                streamWriter.Close();
                            }
                        }
                    }
                }

                s.Close();
            }
            if (delteFile == true)
            {
                File.Delete(zipedFile);
            }
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章