当前位置:网站首页>WinForm版本更新(简易版)
WinForm版本更新(简易版)
2022-07-20 20:48:00 【I Can -Jiang】
1、判断是否更新:
拿数据库的该项目的最大版本号和AssemblyInfo中的版本号做比较判断是否需要更新:
数据库存放版本号表格式:命名空间就是我的系统ID
private bool VersionUpdate()
{
string sql = "select Max(Version) from sys_Version where SystemID = '" + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "' ";
//System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace是用来获取命名空间名称的
DataTable dt;
if (!DB.AF.execSql(sql, sqlconnks, out dt))
{
return false;
}
string newVersion = dt.Rows[0][0].ToString();
Version ver = new Version(newVersion);
Version verson = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
int tm = verson.CompareTo(ver); //版本号比较
if (tm >= 0)
return false;
else
return true;
}
如果数据库的版本号比较大,就提示更新:这里是把CopyUpdate程序放在该解决方案的项目下面
在主程序的Load()下面调用检测更新的函数,如果返回值为True,调用CopyUpdate的程序,结束该线程
if (VersionUpdate())
{
MessageBox.Show("检测到新版本!","更新",MessageBoxButtons.OK,MessageBoxIcon.Information);
string fileName = @"~\"+ System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + @"\CopyUpdate\bin\Debug\CopyUpdate.exe";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = fileName;
p.StartInfo.CreateNoWindow = true;
p.Start();
System.Environment.Exit(System.Environment.ExitCode);
}
接下来就是CopyUpdate的事情了,这块做成了通用的,放在任何一个程序下面都可以用:
思路是从服务器IIS上下载ZIP文件解压覆盖原程序:
这次改了通用版,就是路径不是写死的
先上一下ZIP的类的代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CopyUpdate
{
public class ZipHelper
{
//public static string zipFileFullName = "Update.zip";
public static void Unzip()
{
string str = System.Environment.CurrentDirectory;
string path = str;
for (int i = 0; i < 3; i++)
{
path = Path.GetDirectoryName(path);
}
string[] dirName = path.Split('\\');
//MessageBox.Show("path:" + path);
string _appPath = new DirectoryInfo(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName).Parent.FullName;
string s7z = System.Environment.CurrentDirectory+ @"\7-Zip\7z.exe";
//MessageBox.Show("s7z:" + s7z);
//MessageBox.Show("1:"+ dirName[dirName.Length - 1] + ".zip");
System.Diagnostics.Process pNew = new System.Diagnostics.Process();
pNew.StartInfo.FileName = s7z;
pNew.StartInfo.Arguments = string.Format(" x \"{0}\\{1}\" -y -o\"{0}\"",path, dirName[dirName.Length - 1] + ".zip");
//x "1" -y -o"2" 这段7z命令的意思: x是解压的意思 "{0}"的位置写要解压文件路径"{1}"这个1的位置写要解压的文件名 -y是覆盖的意思 -o是要解压的位置
pNew.Start();
//等待完成
pNew.WaitForExit();
//MessageBox.Show("De:"+path + dirName[dirName.Length - 1] + ".zip");
//删除压缩包
File.Delete([email protected]"\" + dirName[dirName.Length - 1] + ".zip");
}
}
}
然后是更新的主程序的代码:
更新界面:
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CopyUpdate
{
public partial class CopyUpdate : Form
{
private string updateUrl = string.Empty;
private string tempUpdatePath = string.Empty;
public CopyUpdate()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread threadDown = new Thread(new ThreadStart(DownUpdateFile));
threadDown.IsBackground = true;
threadDown.Start();
}
private void DownUpdateFile()
{
string str = System.Environment.CurrentDirectory;
//MessageBox.Show(str);
string path = str;
for (int i = 0; i < 3; i++)
{
path = Path.GetDirectoryName(path);
}
string[] dirName = path.Split('\\');
//dirName[dirName.Length - 1]获取CopyUpdate程序的上级目录,一般按照待更新的目标程序命名
WebClient wcClient = new WebClient();
//线程安全问题 (以不安全的方式访问控件)
CheckForIllegalCrossThreadCalls = false;
string UpdateFile = dirName[dirName.Length - 1] + ".zip";
tempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + dirName[dirName.Length - 1] + "_" + "y" + "_" + "x" + "_" + "m" + "_" + "\\";
//MessageBox.Show(UpdateFile);
string updateFileUrl = "http://172.17.9.19:8080/" + UpdateFile;
long fileLength = 0;
//MessageBox.Show(updateFileUrl);
WebRequest webReq = WebRequest.Create(updateFileUrl);
WebResponse webRes = webReq.GetResponse();
//MessageBox.Show(webRes.ContentLength.ToString());
fileLength = webRes.ContentLength;
//MessageBox.Show(fileLength.ToString());
lbState.Text = "正在下载更新文件,请稍后...";
pbDownFile.Value = 0;
pbDownFile.Maximum = (int)fileLength;
try
{
Stream srm = webRes.GetResponseStream();
StreamReader srmReader = new StreamReader(srm);
byte[] bufferbyte = new byte[fileLength];
int allByte = (int)bufferbyte.Length;
int startByte = 0;
while (fileLength > 0)
{
Application.DoEvents();
int downByte = srm.Read(bufferbyte, startByte, allByte);
if (downByte == 0) { break; };
startByte += downByte;
allByte -= downByte;
pbDownFile.Value += downByte;
float part = (float)startByte / 1024;
float total = (float)bufferbyte.Length / 1024;
int percent = Convert.ToInt32((part / total) * 100);
this.lblspeed.Text = percent.ToString() + "%";
}
string tempPath = tempUpdatePath + UpdateFile;
//MessageBox.Show(tempPath.ToString());
CreateDirtory(tempPath);
FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(bufferbyte, 0, bufferbyte.Length);
srm.Close();
srmReader.Close();
fs.Close();
}
catch (WebException ex)
{
MessageBox.Show("更新文件下载失败!" + ex.Message.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//把文件复制到CopyUpdate上层文件夹下
CopyFile(tempUpdatePath, path);
System.IO.Directory.Delete(tempUpdatePath, true);
//解压覆盖
ZipHelper.Unzip();
if (MessageBox.Show("更新成功", "", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK)
{
string fileName = path + @"\" + dirName[dirName.Length - 1] + @"\bin\Debug\" + dirName[dirName.Length - 1] + ".exe";
//MessageBox.Show(fileName);
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = fileName;
p.StartInfo.CreateNoWindow = true;
p.Start();
System.Environment.Exit(System.Environment.ExitCode);
}
}
//创建目录
private void CreateDirtory(string path)
{
if (!File.Exists(path))
{
string[] dirArray = path.Split('\\');
string temp = string.Empty;
for (int i = 0; i < dirArray.Length - 1; i++)
{
temp += dirArray[i].Trim() + "\\";
if (!Directory.Exists(temp))
Directory.CreateDirectory(temp);
}
}
}
//复制文件;
public void CopyFile(string sourcePath, string objPath)
{
if (!Directory.Exists(objPath))
{
Directory.CreateDirectory(objPath);
}
string[] files = Directory.GetFiles(sourcePath);
for (int i = 0; i < files.Length; i++)
{
string[] childfile = files[i].Split('\\');
File.Copy(files[i], objPath + @"\" + childfile[childfile.Length - 1], true);
}
string[] dirs = Directory.GetDirectories(sourcePath);
for (int i = 0; i < dirs.Length; i++)
{
string[] childdir = dirs[i].Split('\\');
CopyFile(dirs[i], objPath + @"\" + childdir[childdir.Length - 1]);
}
}
}
}
上次挂了下载的连接都没怎么有人看,用到的也不多,这个就不挂了,需要的可以留言
边栏推荐
- 金仓数据库KingbaseES数据库管理员指南--15.3. 管理同义词
- 从去IOE到CIPU,中国云计算要走出自己的路径
- TDSQL PG版节省30%磁盘空间的同时如何保障数据安全?|DB·洞见
- [JS] console command you don't know
- How many bytes do double, float and long occupy?
- Kingbasees database administrator's Guide -- 15.4 Data dictionary view of views, synonyms, and sequences
- The first blog experts to obtain entity certificates on the list
- 【C 练习】求一个数最少需要多少步可变为斐波那契数
- Starfish OS:以现实为纽带,打造元宇宙新范式
- [binary tree] maximum product of split binary tree
猜你喜欢
NFS共享存储服务
There are some tests that you can't test hard enough
[C language] file related operations
【快速上手教程3】疯壳·开源编队无人机-开发环境搭建
mysql数据900W+从17s到300ms是怎么做到的?sql优化的魅力(荣耀典藏版)
6. Stack, stack frame
乘数科技云管控平台适配阿里云 PolarDB,共促云原生数据库生态繁荣
Introduction and use of jsr303
Opportunities and challenges coexist for financial enterprises to go to sea in emerging markets, advance AI ensures its safety and compliance development
从去IOE到CIPU,中国云计算要走出自己的路径
随机推荐
How much do you know about the real results if you don't calibrate before the test?
TCP sliding window explanation (very practical)
广发期货网上开户安全吗?有没有开户指引?
Nacos cluster construction
魑魅魍魎
php 跨域解决方案
Kingbasees database administrator's Guide -- 12 management of schema objects
[JS] console command you don't know
Starfish OS:以现实为纽带,打造元宇宙新范式
Automatic invoice processing - get rid of the shackles of paper and data input, automate workflow and exception handling, and significantly shorten the audit preparation time
Un fantôme.
金仓数据库KingbaseES数据库管理员指南--12模式对象的管理
【C 练习】将字符串中的空格转换为「%20」
Design details related to sap e-commerce cloud Spartacus UI store
【CVA估值训练营】读懂上市公司年报_第二讲
Lora技术助力冷链发展
C语言详解系列——goto语句的讲解和循环语句的简单练习题
When you delete it, you delete it. This kind of capacitance should not have appeared
When a PCB designer meets love, guess how much the impedance in his board changes
Okaleido tiger NFT即将登录Binance NFT平台,后市持续看好