如何让程序自动更新

        自动更新的软件的目的在于让客户不在为了寻找最新软件花费时间。也不用去到开发商的网站上查找。客户端的软件自动会在程序启动前查找服务器上最新的版本。和自己当前软件的版本比较,如果服务器的是最新版本。客户端则进行自动下载、解压、安装。当然了下载是要有网络的,并且用户可以根据提示去完成操作。再也不用为找不到最新版本的软件而头疼。下面是我的大体思路,已经得到了实现:

       1、  写一个webservice,提供一个获取服务器xml中版本的数据的方法。(也可用其他文件格式, 此处举例XML)

       2、  在WinForm应用程序启动的时候,首先访问webservice获取服务器的xml中的版本号,然后获取客户端的xml中的版本号。将两个版本号比较,若服务器中的版本号大,则提示提示可以在线更新应用程序。

       3、  然后客户端自动下载网络上的RAR压缩包到本机的指定位置,进行自动解压缩。解压缩完毕之后,用进程打开所解压过的exe文件进行软件安装。同时关闭客户端软件所在的进程。

  一   web项目中的代码

       首先我给大家先展示下我的web项目中的webservice的代码,这里面跟简单,只有一个方法。项目需要发布到IIS上面。

     1.1 webservice中的代码

          

 [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中的代码

      

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

<Content>

  <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

 

 

 

 

posted @ 2015-02-03 15:11  后缀名  Views(1782)  Comments(0Edit  收藏  举报