winform实现程序自动更新

 程序启动端:

string isAutoUpdate = ConfigurationManager.AppSettings["IsAutoUpdate"].ToString();
            if (isAutoUpdate.Equals("True"))
            {
                string clientVersion = ConfigurationManager.AppSettings["Version"].ToString();//本地版本

                string serverUrl = ConfigurationManager.AppSettings["ServerUrl"].ToString();//服务器地址
                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(serverUrl);
                XmlNodeList nodeList = xdoc.SelectNodes("/ServerUpdate/item");
                string serVersion = xdoc.SelectSingleNode("/ServerUpdate/item/ReleaseVersion").InnerText;//服务器版本
                string releaseUrl = xdoc.SelectSingleNode("/ServerUpdate/item/ReleaseUrl").InnerText;//新版本下载链接
                if (!clientVersion.Equals(serVersion))
                {
                    DialogResult res = MessageBox.Show("有新版本了,是否立即更新?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (res == DialogResult.Yes)
                    {
                        Application.Exit();
                        Process.Start(Application.StartupPath + @"\Update.exe", serverUrl);
                    }
                    else
                    {
                        Application.Run(new Form1());
                    }
                }
                else
                {
                    Application.Run(new Form1());
                }
            }
            else
            {
                Application.Run(new Form1());
            }

自动更新程序:

public partial class UpdateForm : Form
    {
        string appName = string.Empty;//启动程序名称
        string releaseName = string.Empty;//安装包名称
        string serUrl = string.Empty;//服务器地址链接"
        string releaseUrl = string.Empty;//版本连接
        string fileName = string.Empty;//下载至本地定义的文件夹名
        string temp_log = AppDomain.CurrentDomain.BaseDirectory;//log文件地址
        //临时目录(WIN7以及以上在C盘只有对于temp目录有操作权限)
        string tempPath = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), @"AutoUpdate\temp\");
        string bakPath = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), @"AutoUpdate\bak\");//备份地址
        string mainName;//当前程序的名称
        public UpdateForm(string urlPath)
        {
            InitializeComponent();
            this.serUrl = urlPath;
        }

        /// <summary>
        /// 程序主入口
        /// </summary>
        /// <param name="args"></param>
        [STAThread]
        static void Main(string[] args)
        {
            Application.Run(new UpdateForm(args[0]));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                GetServerInfo(this.serUrl);
                label1.Text = "正在更新程序....";
                Process p = Process.GetCurrentProcess();
                mainName = Path.GetFileName(p.MainModule.FileName);
                MessageBox.Show("mainName" + mainName);
                new Thread(new ThreadStart(this.UpdateProgress)).Start();
            }
            catch (Exception ex)
            {
                AddLog("更新程序:Load函数,异常信息:" + ex.Message);
            }
        }

        private void GetServerInfo(string serverUrl)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(serverUrl);
            XmlNodeList nodeList = xdoc.SelectNodes("/ServerUpdate/item");
            releaseUrl = xdoc.SelectSingleNode("/ServerUpdate/item/ReleaseUrl").InnerText;//新版本下载链接
            appName = xdoc.SelectSingleNode("/ServerUpdate/item/AppName").InnerText;
            releaseName = xdoc.SelectSingleNode("/ServerUpdate/item/ReleaseName").InnerText;
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="value"></param>
        public void AddLog(String value)
        {
            if (Directory.Exists(Path.Combine(temp_log, @"log\")) == false)
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(temp_log, @"log\"));
                directoryInfo.Create();
            }
            using (StreamWriter sw = File.AppendText(Path.Combine(temp_log, @"log\update.log")))
            {
                sw.WriteLine(value);
            }
        }

        private void UpdateProgress()
        {
            try
            {
                //0杀死进程
                KillProcessExist();
                //1.更新之前先备份
                BackupFile();
                Thread.Sleep(500);
                //2.备份结束后开始下载文件
                DownLoadFile();
                Thread.Sleep(500);
                //3.开始更新
                UpdateProgram();
                Thread.Sleep(500);
                //4.启动程序
                Start();
                //5.关闭更新程序
                this.Close();
            }
            catch { }
        }

        private void BackupFile()
        {
            AddLog("更新程序:准备备份程序");
            label1.Text = "更新程序:准备备份程序";
            if (!Directory.Exists(bakPath))
            { Directory.CreateDirectory(bakPath); }
            DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            foreach (var item in di.GetFiles())//文件备份
            {
                if (item.Name != mainName)//当前文件不需要备份
                {
                    File.Copy(item.FullName, bakPath + item.Name, true);
                }
            }
            foreach (var item in di.GetDirectories())//文件夹备份
            {
                if (item.Name != "bak" && item.Name != "temp")
                {
                    CopyDirectory(item.FullName, bakPath);
                }
            }
            AddLog("更新程序:备份操作执行完成");
            label1.Text = "更新程序:备份操作执行完成";
        }

        private void DownLoadFile()
        {
            using (WebClient web = new WebClient())
            {
                try
                {
                    if (!Directory.Exists(tempPath))
                    { Directory.CreateDirectory(tempPath); }
                    AddLog("更新程序:下载更新包文件");
                    label1.Text = "更新程序:下载更新包文件";
                    web.DownloadFile(this.releaseUrl, tempPath + releaseName);
                }
                catch (Exception e)
                {
                    label1.Text = "更新程序:更新包文件" + releaseName + "下次失败,本次停止更新,异常信息:" + e.Message;
                    AddLog("更新程序:更新包文件" + releaseName + "下次失败,本次停止更新,异常信息:" + e.Message);
                    this.Close();
                }
            }
        }

        private void UpdateProgram()
        {
            try
            {
                DeleteLocalFile();
                string path = tempPath + releaseName;
                using (ZipFile zip = new ZipFile(path))
                {
                    AddLog("更新程序:解压" + releaseName);
                    label1.Text = "更新程序:解压" + releaseName;
                    zip.ExtractAll(AppDomain.CurrentDomain.BaseDirectory, ExtractExistingFileAction.OverwriteSilently);
                    AddLog("更新程序:" + releaseName + "解压完成");
                    label1.Text = "更新程序:" + releaseName + "解压完成";
                }
            }
            catch (Exception e)
            {
                AddLog("更新程序出现异常:异常信息:" + e.Message);
                AddLog("更新程序:更新失败,进行回滚操作");
                label1.Text = "更新程序出现异常:回滚,异常信息:" + e.Message;
                Restore();
            }
            finally
            {
                label1.Text = "更新程序:删除临时文件" + releaseName;
                AddLog("更新程序:删除临时文件");
                DelTempFile(tempPath + releaseName);
                AddLog("更新程序:临时文件删除完成WareHouse");
                label1.Text = "更新程序:临时文件" + releaseName + "删除完成";
            }
        }

        private void DeleteLocalFile()
        {
            try
            {
                DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                foreach (var item in di.GetFiles())//删除文件
                {
                    AddLog("更新程序:删除文件" + item.Name);
                    if (item.Name != mainName)
                    {
                        if (!item.Name.Contains("DotNetZip.dll"))
                        {
                            File.Delete(item.FullName);
                        }
                    }
                }
                foreach (var item in di.GetDirectories())
                {
                    if (item.Name != "bak" && item.Name != "temp" && item.Name != "log")
                    {
                        item.Delete(true);
                    }
                }
            }
            catch (Exception e)
            {
                AddLog("更新程序:删除文件报错,异常信息:" + e.Message);
            }
        }

        private void Restore()
        {
            DeleteLocalFile();
            try
            {
                CopyDirectory(bakPath, AppDomain.CurrentDomain.BaseDirectory);
            }
            catch (Exception e)
            {
                AddLog("更新程序:回滚失败,异常信息:" + e.Message);
            }
        }

        private void Start()
        {
            AddLog("更新程序:启动" + appName);
            label1.Text = "更新程序:启动" + appName;
            Process.Start(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, appName));
        }

        private void DelTempFile(string path)
        {
            FileInfo file = new FileInfo(path);
            file.Delete();
        }

        

        /// <summary>
        /// 文件拷贝
        /// </summary>
        /// <param name="srcdir">源目录</param>
        /// <param name="desdir">目标目录</param>
        private void CopyDirectory(string srcdir, string desdir)
        {
            string folderName = srcdir.Substring(srcdir.LastIndexOf("\\") + 1);

            string desfolderdir = desdir + "\\" + folderName;

            if (desdir.LastIndexOf("\\") == (desdir.Length - 1))
            {
                desfolderdir = desdir + folderName;
            }
            string[] filenames = Directory.GetFileSystemEntries(srcdir);
            foreach (string file in filenames)// 遍历所有的文件和目录
            {
                if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                {
                    string currentdir = desfolderdir + "\\" + file.Substring(file.LastIndexOf("\\") + 1);
                    if (!Directory.Exists(currentdir))
                    {
                        Directory.CreateDirectory(currentdir);
                    }
                    CopyDirectory(file, desfolderdir);
                }
                else // 否则直接copy文件
                {
                    string srcfileName = file.Substring(file.LastIndexOf("\\") + 1);
                    srcfileName = desfolderdir + "\\" + srcfileName;
                    if (!Directory.Exists(desfolderdir))
                    {
                        Directory.CreateDirectory(desfolderdir);
                    }
                    File.Copy(file, srcfileName, true);
                }
            }
        }

        /// <summary>
        /// 杀掉当前运行的程序进程
        /// </summary>
        /// <param name="programName">程序名称</param>
        public void KillProcessExist()
        {
            Process[] processes = Process.GetProcessesByName(appName);
            foreach (Process p in processes)
            {
                p.Kill();
                p.Close();
            }
        }

    }

写在最后:参考其他博客及自己编写,时间久远,原是草稿,现发出大家共同探讨,若原博主发现,请告知添加参考链接

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、软件开发环境以及开发工具: 框架:.NET Framework 4.0 工具:Visual Studio 2017 插件:DevExpress 18.1.7 环境:IIS 7 二、实现步骤 (1)在项目中创建一个名为WinformAutoUpdate.APP的Winform窗体应用工程,并将默认的Form1.cs窗体文件重命名为MainFrm.cs作为主程序窗体 创建主程序窗体 (2)在项目中再创建一个名为AutoUpdateTask的Winform应用程序工程,并将默认的Form1.cs窗体文件重命名为AutoUpdateTaskFrm.cs作为更新程序窗体 创建更新程序窗体 (3)在更新程序窗体中放入图上所示的相关控件; 进度条控件用于显示更新进度,放入一个Button按钮控件用于用户根据提示进行操作! 实现思路: 1、将更新程序放入磁盘的目录下面,并将其放在已经发布了的IIS中 当用户在运行主程序窗体并点击左上角的更新按钮时,弹出程序更新窗体,并先自动从IIS中拉取updateList.xml文件,然后与本地程序作对比,检测是否需要升级软件; 如果有新版本发布,则点击“立即更新”按钮,程序将从IIS中拉取新发布的ZIP软件包,并自动解压到主程序目录中,覆盖主程序目录中的相关文件(这里值得注意的是,在解压程序之前,我们需要先结束主程序的进程,不然会因主程序进程正在使用而导致报错,另外,我们用到的插件是ICSharpCode.SharpZipLib.dll第三方动态链接库,网上有现成的,可以直接Down下来用);
WinForm程序通用自动更新是指为了方便用户,程序开发者在软件发布后,能够自动检测当前版本,然后下载并安装最新的版本,从而完成软件的更新。 要实现WinForm程序通用自动更新,可以按照以下步骤进行: 1. 开发者需要在软件中添加一个检查更新的功能模块。这个模块可以通过访问开发者服务器上的一个存放软件最新版本信息的文件,来获取当前版本和最新版本的信息。 2. 当用户打开软件或者进行“检查更新”操作时,程序自动调用此模块发起请求,并获取服务器上的最新版本信息。 3. 软件通过比较当前版本和最新版本的信息,判断是否有新版本可供更新。如果有新版本,则提示用户进行更新,并提供下载地址。 4. 用户同意更新后,软件会自动下载最新版本的安装包,并进行安装。在下载和安装过程中,可以显示进度条,以提供给用户更好的用户体验。 5. 安装完成后,软件会自动重启,使更新生效。更新成功后,软件会自动提示用户更新已成功,并展示新版本的特性或者功能变更内容。 为了确保WinForm程序通用自动更新的顺利进行,开发者还需要注意以下几点: 1. 保持服务器稳定性和安全性,确保存放最新版本信息的文件得到正确的维护和更新。可以设置访问权限以防止非法获取和篡改。 2. 版本信息的编写要准确和详细,方便用户了解更新内容,并决定是否需要更新。 3. 下载和安装过程中需要提供异常处理机制,以确保程序能够正确处理各种异常情况,并给出相应的错误提示信息。 通过实现WinForm程序通用自动更新功能,可以让用户十分方便地获得软件最新版本的体验和功能,同时也帮助开发者及时推送修复和优化,提高软件的稳定性和用户满意度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值