C# winform自动更新程序扫盲
2016-04-14 09:46
633 查看
http://bbs.bccn.net/viewthread.php?tid=428255&extra=page%3D1%26amp%3Bfilter%3Ddigest&page=1
自动更新 我直接简单明了的说干的 虚的就不整那么多了,类似这样
思路是一个客户端一个主程序exe 自动更新程序exe 上图
这是自动更新是单独的一个exe 可能有童鞋要问 为啥子是单独一个exe呢 俺的思路是这样 这个exe根据版本号从服务端下载程序 下载完成后 替换主程序的exe 并重新启动主程序exe
看看这个autoupdate的代码吧
主要如下 这里提供一个思路
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Update;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
namespace autoUpdate
{
public partial class Form1 : Form
{
[DllImport("zipfile.dll")]
public static extern int MyZip_ExtractFileAll(string zipfile, string pathname);
public Form1()
{
InitializeComponent();
//清除之前下载来的rar文件
if (File.Exists(Application.StartupPath + "\\Update_autoUpdate.rar"))
{
try
{
File.Delete(Application.StartupPath + "\\Update_autoUpdate.rar");
}
catch (Exception)
{
}
}
if (Directory.Exists(Application.StartupPath + "\\autoupload"))
{
try
{
Directory.Delete(Application.StartupPath + "\\autoupload", true);
}
catch (Exception)
{
}
}
//检查服务端是否有新版本程序
checkUpdate();
timer1.Enabled = true;
}
SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "xinDianClient");
public void checkUpdate()
{
app.UpdateFinish += new UpdateState(app_UpdateFinish);
try
{
if (app.IsUpdate)
{
app.Update();
}
else
{
MessageBox.Show("未检测到新版本!");
Application.Exit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void app_UpdateFinish()
{
//解压下载后的文件
string path = app.FinalZipName;
if (File.Exists(path))
{
//后改的 先解压滤波zip植入ini然后再重新压缩
string dirEcgPath = Application.StartupPath + "\\" + "autoupload";
if (!Directory.Exists(dirEcgPath))
{
Directory.CreateDirectory(dirEcgPath);
}
//开始解压压缩包
MyZip_ExtractFileAll(path, dirEcgPath);
try
{
//复制新文件替换旧文件
DirectoryInfo TheFolder = new DirectoryInfo(dirEcgPath);
foreach (FileInfo NextFile in TheFolder.GetFiles())
{
File.Copy(NextFile.FullName, Application.StartupPath + "\\program\\" + NextFile.Name,true);
}
Directory.Delete(dirEcgPath,true);
File.Delete(path);
//覆盖完成 重新启动程序
path = Application.StartupPath + "\\program";
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "xinDianClient.exe";
process.StartInfo.WorkingDirectory = path;//要掉用得exe路径例如:"C:\windows";
process.StartInfo.CreateNoWindow = true;
process.Start();
Application.Exit();
}
catch (Exception)
{
MessageBox.Show("请关闭系统在执行更新操作!");
Application.Exit();
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "下载文件进度:" + COMMON.CommonMethod.autostep.ToString() + "%";
if (COMMON.CommonMethod.autostep==100)
{
timer1.Enabled = false;
}
}
}
}
简单的说就是检查服务端的是否有新版本 然后呢 下载到本地 并替换在打开
SoftUpdate是一个下载操作类
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using System.Net;
using System.Xml;
using COMMON;
namespace Update
{
/// <summary>
/// 更新完成触发的事件
/// </summary>
public delegate void UpdateState();
/// <summary>
/// 程序更新
/// </summary>
public class SoftUpdate
{
private string download;
private const string updateUrl = "http://33.8.11.117:8019/update.xml";//升级配置的XML文件地址
#region 构造函数
public SoftUpdate() { }
/// <summary>
/// 程序更新
/// </summary>
/// <param name="file">要更新的文件</param>
public SoftUpdate(string file, string softName)
{
this.LoadFile = file;
this.SoftName = softName;
}
#endregion
#region 属性
private string loadFile;
private string newVerson;
private string softName;
private bool isUpdate;
/// <summary>
/// 或取是否需要更新
/// </summary>
public bool IsUpdate
{
get
{
checkUpdate();
return isUpdate;
}
}
/// <summary>
/// 要检查更新的文件
/// </summary>
public string LoadFile
{
get { return loadFile; }
set { loadFile = value; }
}
/// <summary>
/// 程序集新版本
/// </summary>
public string NewVerson
{
get { return newVerson; }
}
/// <summary>
/// 升级的名称
/// </summary>
public string SoftName
{
get { return softName; }
set { softName = value; }
}
private string _finalZipName = string.Empty;
public string FinalZipName
{
get { return _finalZipName; }
set { _finalZipName = value; }
}
#endregion
/// <summary>
/// 更新完成时触发的事件
/// </summary>
public event UpdateState UpdateFinish;
private void isFinish()
{
if (UpdateFinish != null)
UpdateFinish();
}
/// <summary>
/// 下载更新
/// </summary>
public void Update()
{
try
{
if (!isUpdate)
return;
WebClient wc = new WebClient();
string filename = "";
string exten = download.Substring(download.LastIndexOf("."));
if (loadFile.IndexOf(@"\") == -1)
filename = "Update_" + Path.GetFileNameWithoutExtension(loadFile) + exten;
else
filename = Path.GetDirectoryName(loadFile) + "\\Update_" + Path.GetFileNameWithoutExtension(loadFile) + exten;
FinalZipName = filename;
//wc.DownloadFile(download, filename);
wc.DownloadFileAsync(new Uri(download), filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
//wc.Dispose();
}
catch
{
throw new Exception("更新出现错误,网络连接失败!");
}
}
void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
(sender as WebClient).Dispose();
isFinish();
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
CommonMethod.autostep = e.ProgressPercentage;
}
/// <summary>
/// 检查是否需要更新
/// </summary>
public void checkUpdate()
{
try
{
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(updateUrl);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
XmlNode list = xmlDoc.SelectSingleNode("Update");
foreach (XmlNode node in list)
{
if (node.Name == "Soft" && node.Attributes["Name"].Value.ToLower() == SoftName.ToLower())
{
foreach (XmlNode xml in node)
{
if (xml.Name == "Verson")
newVerson = xml.InnerText;
else
download = xml.InnerText;
}
}
}
Version ver = new Version(newVerson);
Version verson = Assembly.LoadFrom(loadFile).GetName().Version;
int tm = verson.CompareTo(ver);
if (tm >= 0)
isUpdate = false;
else
isUpdate = true;
}
catch (Exception ex)
{
throw new Exception("更新出现错误,请确认网络连接无误后重试!");
}
}
/// <summary>
/// 获取要更新的文件
/// </summary>
/// <returns></returns>
public override string ToString()
{
return this.loadFile;
}
}
}
OK 下载的exe写完了 现在呢客户端还差一点就是要在主程序中嵌入它
主程序呢我是这样写的 请不懂的骚年看主要代码
[STAThread]
static void Main()
{
if (checkUpdateLoad())
{
Application.Exit();
return;
}
//执行打开主窗体之类的代码。。。。
}
public static bool checkUpdateLoad()
{
bool result = false;
SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "xinDianClient");
try
{
if (app.IsUpdate && MessageBox.Show("检查到新版本,是否更新?", "版本检查", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string path = Application.StartupPath.Replace("program", "");
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "autoUpdate.exe";
process.StartInfo.WorkingDirectory = path;//要掉用得exe路径例如:"C:\windows";
process.StartInfo.CreateNoWindow = true;
process.Start();
result = true;
}
else
{
result = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
result = false;
}
return result;
}
启动main函数的时候 检查服务端是否有更新 结合SoftUpdate类看就一目了然了
要特别注意目录 为啥子这样说呢 因为有的dll要公用 正在使用就无法替换 所以要分开
所以我的做法是 把主程序放到一个目录 自动更新在外部
[assembly: AssemblyVersion("1.0.0.3")]
[assembly: AssemblyFileVersion("1.0.0.3")]
还有特别要注意的一点
因为要速度嘛 我索性用了.net自带的版本控制 当然也可以自己写
主要在这里 要特别注意一下
OK 现在要部署服务端了 服务端呢 是个zip 我用的zipfile 进行压缩和解压缩的
所以要在服务端部署 最好用这个dll生成一个压缩包
然后部署在服务端iis服务器中
rar 是更新程序 包括要更新的 exe dll之类的
xml内容 一看都明白了把 下载地址 软件名次 版本号
源代码详见:http://download.csdn.net/detail/u011981242/9490547
自动更新 我直接简单明了的说干的 虚的就不整那么多了,类似这样
思路是一个客户端一个主程序exe 自动更新程序exe 上图
这是自动更新是单独的一个exe 可能有童鞋要问 为啥子是单独一个exe呢 俺的思路是这样 这个exe根据版本号从服务端下载程序 下载完成后 替换主程序的exe 并重新启动主程序exe
看看这个autoupdate的代码吧
主要如下 这里提供一个思路
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Update;
using System.Threading;
using System.IO;
using System.Runtime.InteropServices;
namespace autoUpdate
{
public partial class Form1 : Form
{
[DllImport("zipfile.dll")]
public static extern int MyZip_ExtractFileAll(string zipfile, string pathname);
public Form1()
{
InitializeComponent();
//清除之前下载来的rar文件
if (File.Exists(Application.StartupPath + "\\Update_autoUpdate.rar"))
{
try
{
File.Delete(Application.StartupPath + "\\Update_autoUpdate.rar");
}
catch (Exception)
{
}
}
if (Directory.Exists(Application.StartupPath + "\\autoupload"))
{
try
{
Directory.Delete(Application.StartupPath + "\\autoupload", true);
}
catch (Exception)
{
}
}
//检查服务端是否有新版本程序
checkUpdate();
timer1.Enabled = true;
}
SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "xinDianClient");
public void checkUpdate()
{
app.UpdateFinish += new UpdateState(app_UpdateFinish);
try
{
if (app.IsUpdate)
{
app.Update();
}
else
{
MessageBox.Show("未检测到新版本!");
Application.Exit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void app_UpdateFinish()
{
//解压下载后的文件
string path = app.FinalZipName;
if (File.Exists(path))
{
//后改的 先解压滤波zip植入ini然后再重新压缩
string dirEcgPath = Application.StartupPath + "\\" + "autoupload";
if (!Directory.Exists(dirEcgPath))
{
Directory.CreateDirectory(dirEcgPath);
}
//开始解压压缩包
MyZip_ExtractFileAll(path, dirEcgPath);
try
{
//复制新文件替换旧文件
DirectoryInfo TheFolder = new DirectoryInfo(dirEcgPath);
foreach (FileInfo NextFile in TheFolder.GetFiles())
{
File.Copy(NextFile.FullName, Application.StartupPath + "\\program\\" + NextFile.Name,true);
}
Directory.Delete(dirEcgPath,true);
File.Delete(path);
//覆盖完成 重新启动程序
path = Application.StartupPath + "\\program";
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "xinDianClient.exe";
process.StartInfo.WorkingDirectory = path;//要掉用得exe路径例如:"C:\windows";
process.StartInfo.CreateNoWindow = true;
process.Start();
Application.Exit();
}
catch (Exception)
{
MessageBox.Show("请关闭系统在执行更新操作!");
Application.Exit();
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text = "下载文件进度:" + COMMON.CommonMethod.autostep.ToString() + "%";
if (COMMON.CommonMethod.autostep==100)
{
timer1.Enabled = false;
}
}
}
}
简单的说就是检查服务端的是否有新版本 然后呢 下载到本地 并替换在打开
SoftUpdate是一个下载操作类
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using System.Net;
using System.Xml;
using COMMON;
namespace Update
{
/// <summary>
/// 更新完成触发的事件
/// </summary>
public delegate void UpdateState();
/// <summary>
/// 程序更新
/// </summary>
public class SoftUpdate
{
private string download;
private const string updateUrl = "http://33.8.11.117:8019/update.xml";//升级配置的XML文件地址
#region 构造函数
public SoftUpdate() { }
/// <summary>
/// 程序更新
/// </summary>
/// <param name="file">要更新的文件</param>
public SoftUpdate(string file, string softName)
{
this.LoadFile = file;
this.SoftName = softName;
}
#endregion
#region 属性
private string loadFile;
private string newVerson;
private string softName;
private bool isUpdate;
/// <summary>
/// 或取是否需要更新
/// </summary>
public bool IsUpdate
{
get
{
checkUpdate();
return isUpdate;
}
}
/// <summary>
/// 要检查更新的文件
/// </summary>
public string LoadFile
{
get { return loadFile; }
set { loadFile = value; }
}
/// <summary>
/// 程序集新版本
/// </summary>
public string NewVerson
{
get { return newVerson; }
}
/// <summary>
/// 升级的名称
/// </summary>
public string SoftName
{
get { return softName; }
set { softName = value; }
}
private string _finalZipName = string.Empty;
public string FinalZipName
{
get { return _finalZipName; }
set { _finalZipName = value; }
}
#endregion
/// <summary>
/// 更新完成时触发的事件
/// </summary>
public event UpdateState UpdateFinish;
private void isFinish()
{
if (UpdateFinish != null)
UpdateFinish();
}
/// <summary>
/// 下载更新
/// </summary>
public void Update()
{
try
{
if (!isUpdate)
return;
WebClient wc = new WebClient();
string filename = "";
string exten = download.Substring(download.LastIndexOf("."));
if (loadFile.IndexOf(@"\") == -1)
filename = "Update_" + Path.GetFileNameWithoutExtension(loadFile) + exten;
else
filename = Path.GetDirectoryName(loadFile) + "\\Update_" + Path.GetFileNameWithoutExtension(loadFile) + exten;
FinalZipName = filename;
//wc.DownloadFile(download, filename);
wc.DownloadFileAsync(new Uri(download), filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(wc_DownloadFileCompleted);
//wc.Dispose();
}
catch
{
throw new Exception("更新出现错误,网络连接失败!");
}
}
void wc_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
(sender as WebClient).Dispose();
isFinish();
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
CommonMethod.autostep = e.ProgressPercentage;
}
/// <summary>
/// 检查是否需要更新
/// </summary>
public void checkUpdate()
{
try
{
WebClient wc = new WebClient();
Stream stream = wc.OpenRead(updateUrl);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
XmlNode list = xmlDoc.SelectSingleNode("Update");
foreach (XmlNode node in list)
{
if (node.Name == "Soft" && node.Attributes["Name"].Value.ToLower() == SoftName.ToLower())
{
foreach (XmlNode xml in node)
{
if (xml.Name == "Verson")
newVerson = xml.InnerText;
else
download = xml.InnerText;
}
}
}
Version ver = new Version(newVerson);
Version verson = Assembly.LoadFrom(loadFile).GetName().Version;
int tm = verson.CompareTo(ver);
if (tm >= 0)
isUpdate = false;
else
isUpdate = true;
}
catch (Exception ex)
{
throw new Exception("更新出现错误,请确认网络连接无误后重试!");
}
}
/// <summary>
/// 获取要更新的文件
/// </summary>
/// <returns></returns>
public override string ToString()
{
return this.loadFile;
}
}
}
OK 下载的exe写完了 现在呢客户端还差一点就是要在主程序中嵌入它
主程序呢我是这样写的 请不懂的骚年看主要代码
[STAThread]
static void Main()
{
if (checkUpdateLoad())
{
Application.Exit();
return;
}
//执行打开主窗体之类的代码。。。。
}
public static bool checkUpdateLoad()
{
bool result = false;
SoftUpdate app = new SoftUpdate(Application.ExecutablePath, "xinDianClient");
try
{
if (app.IsUpdate && MessageBox.Show("检查到新版本,是否更新?", "版本检查", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
string path = Application.StartupPath.Replace("program", "");
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "autoUpdate.exe";
process.StartInfo.WorkingDirectory = path;//要掉用得exe路径例如:"C:\windows";
process.StartInfo.CreateNoWindow = true;
process.Start();
result = true;
}
else
{
result = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
result = false;
}
return result;
}
启动main函数的时候 检查服务端是否有更新 结合SoftUpdate类看就一目了然了
要特别注意目录 为啥子这样说呢 因为有的dll要公用 正在使用就无法替换 所以要分开
所以我的做法是 把主程序放到一个目录 自动更新在外部
[assembly: AssemblyVersion("1.0.0.3")]
[assembly: AssemblyFileVersion("1.0.0.3")]
还有特别要注意的一点
因为要速度嘛 我索性用了.net自带的版本控制 当然也可以自己写
主要在这里 要特别注意一下
OK 现在要部署服务端了 服务端呢 是个zip 我用的zipfile 进行压缩和解压缩的
所以要在服务端部署 最好用这个dll生成一个压缩包
然后部署在服务端iis服务器中
rar 是更新程序 包括要更新的 exe dll之类的
<?xml version="1.0" encoding="utf-8" ?> <Update> <Soft Name="update"> <Verson>1.0.0.3</Verson> <DownLoad>http://33.8.11.117:8079/update.rar</DownLoad> </Soft> </Update>
xml内容 一看都明白了把 下载地址 软件名次 版本号
源代码详见:http://download.csdn.net/detail/u011981242/9490547
相关文章推荐
- C#中is与as的区别分析
- leetcode 15:3 Sum (C#语言版)
- LeetCode #4 Median of Two Sorted Arrays C# Solution
- VS2010 Coredump文件生成
- C#复制、粘贴文本信息到剪贴板
- C#多线程——Timer
- C#多线程——前台线程和后台线程
- C#多线程——创建线程
- C#多线程——多线程访问共同的代码或者对象
- C#多线程——线程池和回调函数
- C# Winform工程省市县三级行政区联动 --XML
- C#中的代码书写规范以及命名规范
- C#读取Excel数据到数组
- 0基础学C#教程2--------C#如何调用excel,试用最新版的excel
- C# 结构体直接赋值的问题
- C#中struct的字节对齐、转换操作和复制为二进制数据(byte[])
- c#中关于结构体和字节数组转化
- 关于C# byte[]与struct的转换
- 【C#】delegate(委托) 将方法作为参数在类class 之间传递
- C#枚举