public partial class MyUpdate : Form
{
private string urlPath = "";
private string Filename = string.Empty;
public MyUpdate(string url)
{
InitializeComponent();
this.urlPath = url;
}
private void button1_Click(object sender, EventArgs e)
{
DownFile(urlPath + "client.exe", Filename + "\\client.exe", this.progressBar1, this.label1);
}
/// <summary>
/// 下载方法(带进度条)
/// </summary>
/// <param name="URL">服务器URL地址</param>
/// <param name="Filename">存放到本地的路径</param>
/// <param name="Prog">进度条</param>
public static void DownFile(string URL, string Filename, ProgressBar Prog, Label label1)
{
float percent = 0;
try
{
HttpWebRequest Myrq = (HttpWebRequest)HttpWebRequest.Create(URL);
HttpWebResponse myrp = (HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
if (Prog != null)
{
Prog.Maximum = (int)totalBytes;
}
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new FileStream(Filename, FileMode.Append, FileAccess.Write);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
Application.DoEvents();
so.Write(by, 0, osize);
Prog.Value = (int)totalDownloadedByte;
osize = st.Read(by, 0, (int)by.Length);
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
label1.Text = "更新进度" + percent.ToString() + "%";
System.Windows.Forms.Application.DoEvents();
}
so.Close();
st.Close();
DialogResult dr = MessageBox.Show("下载完成,是否要打开程序", "下载提示:", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button3);
if (dr == DialogResult.Yes)
{
System.Diagnostics.Process.Start("client.exe", "");
Application.Exit();
}
else
{
Console.WriteLine("放弃程序更新");
Application.Exit();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
}
}
}