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();
            }
        }

    }

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值