c# winform 自动升级

前一阵项目组需要一个自动升级的功能,让其他成员做了此模块,现想研究下所以百度了下,应该是按以下思路进行的!

以下转自:http://ruantnt.blog.163.com/blog/static/190525452201181421440361/

 

winform自动升级程序示例源码下载

客户端思路:

1、新建一个配置文件Update.ini,用来存放软件的客户端版本:

[update]
version=2011-09-09 15:26

2、新建一个单独的客户端升级程序Update.exe:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Net;

using System.Threading;

using System.Diagnostics;

using System.IO;

 

namespace Update

{

    publicpartialclassFrmUpdate : Form

    {

        //关闭进度条的委托

        publicdelegatevoidCloseProgressDelegate();

        //声明关闭进度条事件

        publiceventCloseProgressDelegate CloseProgress;

        UpdateService.Service service = null;//webservice服务

        WebClient wc = null;

        string url;//获取下载地址

        string[] zips;//获取升级压缩包

        int zipsIndex = 0;//当前正在下载的zips下标

 

        long preBytes = 0;//上一次下载流量

        long currBytes = 0;//当前下载流量

        public FrmUpdate()

        {

            InitializeComponent();

            service = new UpdateService.Service();//webservice服务

            url = service.GetUrl();//获取下载地址               

            zips = service.GetZips();//获取升级压缩包

        }

 

        privatevoid FrmUpdate_Load(object sender, EventArgs e)

        {

            try

            {

                //用子线程工作

                Thread t = newThread(newThreadStart(DownLoad));

                t.IsBackground = true;//设为后台线程

                t.Start();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

 

        ///<summary>

        ///下载更新

        ///</summary>

        privatevoid DownLoad()

        {

            try

            {

                CloseProgress += newCloseProgressDelegate(FrmUpdate_CloseProgress);

                if (zips.Length > 0)

                {

                    wc = newWebClient();

                    wc.DownloadProgressChanged += newDownloadProgressChangedEventHandler(wc_DownloadProgressChanged);

                    wc.DownloadFileCompleted += newAsyncCompletedEventHandler(wc_DownloadFileCompleted);

                    wc.DownloadFileAsync(newUri(url + zips[zipsIndex]), zips[zipsIndex]);

                }

                else

                {

                    FrmUpdate_CloseProgress();//调用关闭进度条事件

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

        ///<summary>

        ///下载完成后触发

        ///</summary>

        void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)

        {

            zipsIndex++;

            if (zipsIndex < zips.Length)

            {

                //继续下载下一个压缩包

                wc = newWebClient();

                wc.DownloadProgressChanged += newDownloadProgressChangedEventHandler(wc_DownloadProgressChanged);

                wc.DownloadFileCompleted += newAsyncCompletedEventHandler(wc_DownloadFileCompleted);

                wc.DownloadFileAsync(newUri(url + zips[zipsIndex]), zips[zipsIndex]);

            }

            else

            {

                //解压

                int maximum = ZipClass.GetMaximum(zips);

                foreach (string zip in zips)

                {

                    ZipClass.UnZip(Application.StartupPath + @"\" + zip, "", maximum, FrmUpdate_SetProgress);

                    File.Delete(Application.StartupPath + @"\" + zip);

                }

                FrmUpdate_CloseProgress();//调用关闭进度条事件

            }

        }

        ///<summary>

        ///下载时触发

        ///</summary>

        void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)

        {

            if (this.InvokeRequired)

            {

                this.Invoke(newDownloadProgressChangedEventHandler(wc_DownloadProgressChanged), newobject[] { sender, e });

            }

            else

            {

                label1.Text = "正在下载自解压包" + zips[zipsIndex] + "(" + (zipsIndex + 1).ToString() + "/" + zips.Length + ")";

                progressBar1.Maximum = 100;

                progressBar1.Value = e.ProgressPercentage;

 

                currBytes = e.BytesReceived;//当前下载流量

            }

        }

        ///<summary>

        ///解压时进度条事件

        ///</summary>

        ///<param name="maximum">进度条最大值</param>

        privatevoid FrmUpdate_SetProgress(int maximum, string msg)

        {

            if (this.InvokeRequired)

            {

                this.Invoke(new ZipClass.SetProgressDelegate(FrmUpdate_SetProgress), newobject[] { maximum, msg });

            }

            else

            {

                if (zipsIndex == zips.Length)

                {

                    //刚压缩完

                    progressBar1.Value = 0;

                    zipsIndex++;

                }

                label1.Text = "正在解压" + msg + "(" + (progressBar1.Value + 1).ToString() + "/" + maximum + ")";

                progressBar1.Maximum = maximum;

                progressBar1.Value++;

            }

        }

 

        ///<summary>

        ///实现关闭进度条事件

        ///</summary>

        privatevoid FrmUpdate_CloseProgress()

        {

            if (this.InvokeRequired)

            {

                this.Invoke(newCloseProgressDelegate(FrmUpdate_CloseProgress), null);

            }

            else

            {

                if (wc != null)

                {

                    wc.Dispose();

                }

                if (zips.Length > 0)

                {

                    MessageBox.Show("升级成功!");

                }

                else

                {

                    MessageBox.Show("未找到升级包!");

                }

                IniClass ini = new IniClass(Application.StartupPath + @"\Update.ini");

                string serviceVersion = service.GetVersion();//服务端版本

                ini.IniWriteValue("update", "version", serviceVersion);//更新成功后将版本写入配置文件

                Application.Exit();//退出升级程序

                Process.Start("Main.exe");//打开主程序Main.exe

            }

        }

 

        //1秒计算一次速度

        privatevoid timer1_Tick(object sender, EventArgs e)

        {

            this.Text = ((currBytes - preBytes) / 1024).ToString() + "kb/s";//速度

            preBytes = currBytes;//上一次下载流量

        }

    }

}

解压类ZipClass.cs:引用 ICSharpCode.SharpZipLib.dll

using System;

using System.Collections.Generic;

using System.Text;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Windows.Forms;

using System.IO;

using ICSharpCode.SharpZipLib;

using ICSharpCode.SharpZipLib.Checksums;

using ICSharpCode.SharpZipLib.Zip;

 

namespace Update

{

    publicclassZipClass

    {

        //设置进度条的委托

        publicdelegatevoidSetProgressDelegate(int maximum, string msg);

        #region 解压

        ///<summary>  

        ///功能:解压zip格式的文件。  

        ///</summary>  

        ///<param name="zipFilePath">压缩文件路径,全路径格式</param>  

        ///<param name="unZipDir">解压文件存放路径,全路径格式,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>  

        ///<param name="err">出错信息</param>  

        ///<returns>解压是否成功</returns>  

        publicstaticbool UnZip(string zipFilePath, string unZipDir, int maximum, SetProgressDelegate setProgressDelegate)

        {

            if (zipFilePath == string.Empty)

            {

                thrownew System.IO.FileNotFoundException("压缩文件不不能为空!");

            }

            if (!File.Exists(zipFilePath))

            {

                thrownew System.IO.FileNotFoundException("压缩文件: " + zipFilePath + " 不存在!");

            }

            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹  

            if (unZipDir == string.Empty)

                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), "");

            if (!unZipDir.EndsWith("//"))

                unZipDir += "//";

            if (!Directory.Exists(unZipDir))

                Directory.CreateDirectory(unZipDir);

 

            try

            {

                using (ZipInputStream s = newZipInputStream(File.OpenRead(zipFilePath)))

                {

                    ZipEntry theEntry;

                    while ((theEntry = s.GetNextEntry()) != null)

                    {

                        string directoryName = Path.GetDirectoryName(theEntry.Name);

                        string fileName = Path.GetFileName(theEntry.Name);

                        if (directoryName.Length > 0)

                        {

                            Directory.CreateDirectory(unZipDir + directoryName);

                        }

                        if (!directoryName.EndsWith("//"))

                            directoryName += "//";

                        if (fileName != String.Empty)

                        {

                            using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))

                            {

 

                                int size = 2048;

                                byte[] data = newbyte[2048];

                                while (true)

                                {

                                    size = s.Read(data, 0, data.Length);

                                    if (size > 0)

                                    {

                                        streamWriter.Write(data, 0, size);

                                    }

                                    else

                                    {

                                        setProgressDelegate(maximum, theEntry.Name);

                                        break;

                                    }

                                }

                            }

                        }

                    }//while  

                }

            }

            catch (Exception ex)

            {

                thrownewException(ex.Message);

            }

            returntrue;

        }//解压结束 

        #endregion

 

        publicstaticint GetMaximum(string[] zips)

        {

            int maximum = 0;

            ZipInputStream s = null;

            ZipEntry theEntry = null;

            foreach (string zip in zips)

            {

                s = newZipInputStream(File.OpenRead(Application.StartupPath + @"\" + zip));

                while ((theEntry = s.GetNextEntry()) != null)

                {

                    if (Path.GetFileName(theEntry.Name) != "")

                    {

                        maximum++;

                    }

                }

            }

            if (s != null)

            {

                s.Close();

            }

            return maximum;

        }

    }

}

 3、将update.ini和Update.exe复制到主程序目录,主程序登录时判断客户端版本是否与服务端版本相同,如不同,则做升级:

IniClass ini = newIniClass(Application.StartupPath + @"\Update.ini");

                UpdateService.Service service = new UpdateService.Service();

                string clientVersion = ini.IniReadValue("update", "version");//客户端版本

                string serviceVersion = service.GetVersion();//服务端版本

                if (clientVersion != serviceVersion)

                {

                    DialogResult dialogResult = MessageBox.Show("有新版本,是否更新?", "升级", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

                    if (dialogResult == DialogResult.OK)

                    {

                        Application.Exit();

                        Process.Start("Update.exe");

                    }

                }

                else

                {

                    MessageBox.Show("已更新至最高版本!");

                }

服务端思路:

1、新建一个Web Service,在Web.Config中配置:

  <connectionStrings>

    <!--版本号-->

    <addname="version"connectionString="2011-09-20 15:17"/>

    <!--下载地址-->

    <addname="url"connectionString ="http://localhost:8546/WebSite/"/>

    <!--下载目录,最好为一级目录免得麻烦-->

    <addname="directory"connectionString ="UpdateFile"/>

  </connectionStrings>

2、在Service.cs写入以下代码:

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.IO;

using System.Configuration;

 

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

publicclassService : System.Web.Services.WebService

{ 

    public Service()

    { 

        //如果使用设计的组件,请取消注释以下行

        //InitializeComponent();

    }

    ///<summary>

    ///获取版本号

    ///</summary>

    ///<returns>更新版本号</returns>

    [WebMethod]

    publicstring GetVersion()

    {

        returnConfigurationManager.ConnectionStrings["version"].ConnectionString;

    }

    ///<summary>

    ///获取下载地址

    ///</summary>

    ///<returns>下载地址</returns>

    [WebMethod]

    publicstring GetUrl()

    {

        returnConfigurationManager.ConnectionStrings["url"].ConnectionString + ConfigurationManager.ConnectionStrings["directory"].ConnectionString + "/";

    }

    ///<summary>

    ///获取下载zip压缩包

    ///</summary>

    ///<returns>下载zip压缩包</returns>

    [WebMethod]

    publicstring[] GetZips()

    {

        string folder = HttpRuntime.AppDomainAppPath + ConfigurationManager.ConnectionStrings["directory"].ConnectionString;

        string[] zips = Directory.GetFileSystemEntries(folder);

        for (int i = 0; i < zips.Length; i++)

        {

            zips[i] = Path.GetFileName(zips[i]);

        }

        return zips;

    }

}


 3、发布WebSerivce,在IIS中配置好,并成功运行

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
SimpAutoUpdater c#自动升级 模块源码 可以集成到自己程序: 首先在VS中为当前的主程序项目添加引用,引用“客户端”中的“SimpleUpdater.exe”。 在VS中,点开“解决方案管理器”中相应项目的“属性”节点,打开 AssemblyInfo.cs 文件,在最下面添加上一行自动更新声明: //--添加这行标记表示支持自动更新, 后面的网址为自动更新的根目录. [assembly: FSLib.App.SimpleUpdater.Updateable("http://ls.com/update.xml")] 这步是必须的,否则请求检查更新时会抛出异常;代码中的网址即上面提到的能访问到xml文件的网址。 如果您希望更加简单的使用而不用去加这样的属性,或者您想程序运行的时候自定义,您可以通过下列方式的任何一种方式取代上面的属性声明: 使用 FSLib.App.SimpleUpdater.Updater.CheckUpdateSimple("升级网址") 的重载方法。这个重载方法允许你传入一个升级包的地址; 在检查前手动设置 FSLib.App.SimpleUpdater.Updater.UpdateUrl 属性。这是一个静态属性,也就是说,您并不需要创建 FSLib.App.SimpleUpdater.Updater.UpdateUrl 的对象实例就可以修改它。 无论使用哪种方式,请确保在检查更新前,地址已经设置。 到这里,准备工作即告完成,为代码添加上检查更新的操作即可。 static class Program { /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var updater = FSLib.App.SimpleUpdater.Updater.Instance; //当检查发生错误时,这个事件会触发 updater.Error += new EventHandler(updater_Error); //没有找到更新的事件 updater.NoUpdatesFound += new EventHandler(updater_NoUpdatesFound); //找到更新的事件.但在此实例中,找到更新会自动进行处理,所以这里并不需要操作 //updater.UpdatesFound += new EventHandler(updater_UpdatesFound); //开始检查更新-这是最简单的模式.请现在 assemblyInfo.cs 中配置更新地址,参见对应的文件. FSLib.App.SimpleUpdater.Updater.CheckUpdateSimple(); /* * 如果您希望更加简单的使用而不用去加这样的属性,或者您想程序运行的时候自定义,您可以通过下列方式的任何一种方式取代上面的属性声明: * 使用Updater.CheckUpdateSimple 的重载方法。这个重载方法允许你传入一个升级包的地址; * 在检查前手动设置 FSLib.App.SimpleUpdater.Updater.UpdateUrl 属性。这是一个静态属性,也就是说,您并不需要创建 FSLib.App.SimpleUpdater.Updater.UpdateUrl 的对象实例就可以修改它。 */ FSLib.App.SimpleUpdater.Updater.CheckUpdateSimple("升级网址"); Application.Run(new Form1()); } static void updater_UpdatesFound(object sender, EventArgs e) { } static void updater_NoUpdatesFound(object sender, EventArgs e) { System.Windows.Forms.MessageBox.Show("没有找到更新"); } static void updater_Error(object sender, EventArgs e) { var updater = sender as FSLib.App.SimpleUpdater.Updater; System.Windows.Forms.MessageBox.Show(updater.Exception.ToString()); } }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值