最近在项目的时候不断的版本更新,客户很烦,偶亦很忙,于是就想添加个自动更新的东东在程序里,客户与我皆大欢喜:
废话少说了,先上代码:
首先修改解决方案名称\Properties\AssemblyInfo.cs文件中的版本信息
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 内部版本号
// 修订号
//
[assembly: AssemblyVersion("1.0.0.1")]
[assembly: AssemblyFileVersion("1.0.0.1")]
而后在数据库里添加一个当前版本的版本号,程序加载的时候去识别当前版本与数据库中的版本比较:
string currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
getOtherParam();
string sql = "select versionID from versionmanager where create_dt=(select max(create_dt) from versionmanager) ";
DataOperate dataOper = new DataOperate();
DataTable table = dataOper.getDatatableExcuteSQL(sql);
if (table.Rows.Count != 1)
{
MessageBox.Show("版本信息表出现异常,请核实");
return;
}
string latestVersion = table.Rows[0]["VERSIONID"].ToString();
if (currentVersion.Equals(latestVersion) == false)
{
DialogResult result = MessageBox.Show("有较新的版本可以下载,现在去下载吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.OK)
{
string path = Application.StartupPath;
int i = path.IndexOf("bin", 0, StringComparison.InvariantCultureIgnoreCase);
string binPath = path.Substring(0, i) ;
Application.Exit();
Application.ExitThread();
System.Diagnostics.Process.Start(binPath + @"\UpdateProg.exe");
}
else
{
Application.Run(new LoginForm());
}
}
else
{
Application.Run(new LoginForm());
}
更新exe文件的编写:
private void UpdateForm_Load(object sender, EventArgs e)
{
string path = Application.StartupPath;
DeleteInDir(path + @"\bin");
//modifyFilename(path +@"\bin");
//下载并解压新文件
string tempFolder = path; //下载的目录
bool isDownLoad = false;
try
{
this.label1.Text = "开始下载更新程序……";
FTPClient.DownLoad(tempFolder); //下载
this.label1.Text = "正在解压文件……";
string s = FTPClient.unCompressRAR(tempFolder, tempFolder, "bin.rar"); //解压
isDownLoad = true;
}
catch (Exception ex)
{
MessageBox.Show("从ftp下载文件失败,请关闭防火墙以及代理~" + ex.ToString());
isDownLoad = false;
Application.Exit();
}
if (isDownLoad == true)
{
Application.Exit();
System.Diagnostics.Process.Start(path + @"\bin\release" + @"\江苏电信ODS网格管理.exe");
}
}
private void DeleteInDir(string szDirPath)
{
if (szDirPath.Trim() == "" || !Directory.Exists(szDirPath))
return;
DirectoryInfo dirInfo = new DirectoryInfo(szDirPath);
FileInfo[] fileInfos = dirInfo.GetFiles();
if (fileInfos != null && fileInfos.Length > 0)
{
foreach (FileInfo fileInfo in fileInfos)
{
//DateTime.Compare( fileInfo.LastWriteTime,DateTime.Now);
File.Delete(fileInfo.FullName); //删除文件
}
}
DirectoryInfo[] dirInfos = dirInfo.GetDirectories();
if (dirInfos != null && dirInfos.Length > 0)
{
foreach (DirectoryInfo childDirInfo in dirInfos)
{
this.DeleteInDir(childDirInfo.FullName); //递归
}
}
//Directory.Delete(dirInfo.FullName, true); //删除目录
}

浙公网安备 33010602011771号