自动升级程序
主程序如何检查是否有最新版本,我就不写了。
当检查到有新版本,就关闭主程序,运行这个新程序。这是我自己现在用的升级程序,分享下,有什么不好的地方大家提出来,我们一起进步。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 System.IO;
using System.Net;
using System.Data.SqlClient;
using System.Configuration;
namespace updateWinform
{
publicpartialclass Form1 : Form
{
public Form1()
{
InitializeComponent();
}
privatevoid Form1_Load(object sender, EventArgs e)
{
}
//开始下载的按钮
privatevoid btnOK_Click(object sender, EventArgs e)
{
DownLoadFile();
this.btnOK.Enabled =false;
}
privatevoid DownLoadFile()
{
//获取本次更新所需要下载的文件
Dictionary<string, string> dic = GetLoadFile();
dic.ToList().ForEach(p =>
{
ListViewItem item =new ListViewItem();
item.Text = p.Key;//文件名
item.SubItems.Add(p.Value);//大小
listView1.Items.Add(item);
});
try
{
WebClient client =new WebClient();
if (!Directory.Exists(Application.StartupPath +@"\update"))
{
Directory.CreateDirectory(Application.StartupPath +@"\update");
}
for (int i =0; i <=this.listView1.Items.Count -1; i++)
{
string hosturl = ConfigurationManager.AppSettings["url"].ToString();
string fileName =this.listView1.Items[i].SubItems[0].Text;
string url = hosturl + fileName;
string file = Application.StartupPath +"\\update\\"+ fileName;
this.label2.Visible =true;
this.label2.Text ="正在下载:"+ fileName;
Stream myStream = client.OpenRead(url);
byte[] bBuffer =newbyte[10240];
int nRealCount =0;
DateTime dtStart = DateTime.Now;
TimeSpan ts;
int lenth = Convert.ToInt32(this.listView1.Items[i].SubItems[1].Text.ToString());
int cur =0;
progressBar1.Value =0;
FileStream fs =new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
int value =0;
int counter =1;
do
{
if (counter %10==0)
{
ts = DateTime.Now - dtStart;
int perSecondsValue = (int)((double)value / (ts.TotalMilliseconds /1000)) /1024;
//this.label3.Text = "速度:" + perSecondsValue + " k/s";
dtStart = DateTime.Now;
value =0;
}
nRealCount = myStream.Read(bBuffer, 0, bBuffer.Length);
if (nRealCount >0)
{
fs.Write(bBuffer, 0, nRealCount);
}
cur = cur + nRealCount;
double pe = cur;
pe = pe *100/ lenth;
int va = Convert.ToInt32(pe);
progressBar1.Value = va;
this.label2.Text ="正在下载:"+ fileName +""+ cur /1024+" KB/"+ lenth /1024+"
KB";
value += nRealCount;
counter++;
}
while (nRealCount >0);
fs.Close();
this.listView1.Items[i].SubItems.Add("已下载");
}
this.label2.Text ="正在更新文件,请稍后...";
string[] fileDir = Directory.GetFileSystemEntries(Application.StartupPath +@"\update");
foreach (string str in fileDir)
{
int pos = str.LastIndexOf(@"\");
string FileName = str.Substring(pos);
string FilePath = Application.StartupPath + FileName;
File.Copy(str, FilePath, true);
}
this.label2.Text ="正在删除临时文件,请稍后...";
System.IO.Directory.Delete(Application.StartupPath +@"\update", true);
this.label2.Text ="程序更新已完成!";
this.btnExit.Text ="完成(&F)";
}
catch (Exception errMsg)
{
MessageBox.Show(errMsg.Message);
}
}
privatevoid btnExit_Click(object sender, EventArgs e)
{
if (btnExit.Text.Trim().Equals("取消"))
{
Application.Exit();
}
else
{
System.Diagnostics.Process.Start(Application.StartupPath +"\\"+"主程序.exe");
Application.Exit();
}
}
//从数据库读取所需要下载的文件
public Dictionary<string, string> GetLoadFile()
{
Dictionary<string, string> dic =new Dictionary<string, string>();
string sql ="select top 1 LoadFile from 表 order by id desc";
SqlDataReader read = DBHelper.GetReader(sql);
string b ="";
while (read.Read())
{
b = (string)read["LoadFile"];
}
read.Close();
read.Dispose();
string[] load = b.Split(';');
load.ToList().ForEach(p =>
{
string[] detail = p.Split(',');
//ditail[0]:下载的文件名 detail[1]:下载文件的大小,以便于计算进度条
dic.Add(detail[0], detail[1]);
});
return dic;
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Data.SqlClient;
using System.Configuration;
namespace updateWinform
{
publicpartialclass Form1 : Form
{
public Form1()
{
InitializeComponent();
}
privatevoid Form1_Load(object sender, EventArgs e)
{
}
//开始下载的按钮
privatevoid btnOK_Click(object sender, EventArgs e)
{
DownLoadFile();
this.btnOK.Enabled =false;
}
privatevoid DownLoadFile()
{
//获取本次更新所需要下载的文件
Dictionary<string, string> dic = GetLoadFile();
dic.ToList().ForEach(p =>
{
ListViewItem item =new ListViewItem();
item.Text = p.Key;//文件名
item.SubItems.Add(p.Value);//大小
listView1.Items.Add(item);
});
try
{
WebClient client =new WebClient();
if (!Directory.Exists(Application.StartupPath +@"\update"))
{
Directory.CreateDirectory(Application.StartupPath +@"\update");
}
for (int i =0; i <=this.listView1.Items.Count -1; i++)
{
string hosturl = ConfigurationManager.AppSettings["url"].ToString();
string fileName =this.listView1.Items[i].SubItems[0].Text;
string url = hosturl + fileName;
string file = Application.StartupPath +"\\update\\"+ fileName;
this.label2.Visible =true;
this.label2.Text ="正在下载:"+ fileName;
Stream myStream = client.OpenRead(url);
byte[] bBuffer =newbyte[10240];
int nRealCount =0;
DateTime dtStart = DateTime.Now;
TimeSpan ts;
int lenth = Convert.ToInt32(this.listView1.Items[i].SubItems[1].Text.ToString());
int cur =0;
progressBar1.Value =0;
FileStream fs =new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write);
int value =0;
int counter =1;
do
{
if (counter %10==0)
{
ts = DateTime.Now - dtStart;
int perSecondsValue = (int)((double)value / (ts.TotalMilliseconds /1000)) /1024;
//this.label3.Text = "速度:" + perSecondsValue + " k/s";
dtStart = DateTime.Now;
value =0;
}
nRealCount = myStream.Read(bBuffer, 0, bBuffer.Length);
if (nRealCount >0)
{
fs.Write(bBuffer, 0, nRealCount);
}
cur = cur + nRealCount;
double pe = cur;
pe = pe *100/ lenth;
int va = Convert.ToInt32(pe);
progressBar1.Value = va;
this.label2.Text ="正在下载:"+ fileName +""+ cur /1024+" KB/"+ lenth /1024+"
KB";
value += nRealCount;
counter++;
}
while (nRealCount >0);
fs.Close();
this.listView1.Items[i].SubItems.Add("已下载");
}
this.label2.Text ="正在更新文件,请稍后...";
string[] fileDir = Directory.GetFileSystemEntries(Application.StartupPath +@"\update");
foreach (string str in fileDir)
{
int pos = str.LastIndexOf(@"\");
string FileName = str.Substring(pos);
string FilePath = Application.StartupPath + FileName;
File.Copy(str, FilePath, true);
}
this.label2.Text ="正在删除临时文件,请稍后...";
System.IO.Directory.Delete(Application.StartupPath +@"\update", true);
this.label2.Text ="程序更新已完成!";
this.btnExit.Text ="完成(&F)";
}
catch (Exception errMsg)
{
MessageBox.Show(errMsg.Message);
}
}
privatevoid btnExit_Click(object sender, EventArgs e)
{
if (btnExit.Text.Trim().Equals("取消"))
{
Application.Exit();
}
else
{
System.Diagnostics.Process.Start(Application.StartupPath +"\\"+"主程序.exe");
Application.Exit();
}
}
//从数据库读取所需要下载的文件
public Dictionary<string, string> GetLoadFile()
{
Dictionary<string, string> dic =new Dictionary<string, string>();
string sql ="select top 1 LoadFile from 表 order by id desc";
SqlDataReader read = DBHelper.GetReader(sql);
string b ="";
while (read.Read())
{
b = (string)read["LoadFile"];
}
read.Close();
read.Dispose();
string[] load = b.Split(';');
load.ToList().ForEach(p =>
{
string[] detail = p.Split(',');
//ditail[0]:下载的文件名 detail[1]:下载文件的大小,以便于计算进度条
dic.Add(detail[0], detail[1]);
});
return dic;
}
}
}