winformC# 自动更新
Posted 浅时光
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winformC# 自动更新相关的知识,希望对你有一定的参考价值。
用IIS或者是Tomcat搭建一个Web服务器,因为没有涉及到动态页面,所以用什么服务器无所谓,网上有太多资料,这里不再赘述。
废话不多说,直接上代码。
HttpHelper, 访问网页,下载文件等
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; namespace AutoUpdate { class HttpHelper { //以GET方式抓取远程页面内容 public static string Get_Http(string tUrl) { string strResult; try { HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(tUrl); hwr.Timeout = 300; HttpWebResponse hwrs = (HttpWebResponse)hwr.GetResponse(); Stream myStream = hwrs.GetResponseStream(); StreamReader sr = new StreamReader(myStream, Encoding.Default); StringBuilder sb = new StringBuilder(); while (-1 != sr.Peek()) { sb.Append(sr.ReadLine() + "\r\n"); } strResult = sb.ToString(); hwrs.Close(); } catch (Exception ee) { strResult = ee.Message; } return strResult; } //以POST方式抓取远程页面内容 //postData为参数列表 public static string Post_Http(string url, string postData, string encodeType) { string strResult = null; try { Encoding encoding = Encoding.GetEncoding(encodeType); byte[] POST = encoding.GetBytes(postData); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = POST.Length; Stream newStream = myRequest.GetRequestStream(); newStream.Write(POST, 0, POST.Length); //设置POST newStream.Close(); // 获取结果数据 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default); strResult = reader.ReadToEnd(); } catch (Exception ex) { strResult = ex.Message; } return strResult; } /// <summary> /// c#,.net 下载文件 /// </summary> /// <param name="URL">下载文件地址</param> /// /// <param name="Filename">下载后的存放地址</param> /// <param name="Prog">用于显示的进度条</param> /// public static void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1,string description) { float percent = 0; try { System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL); System.Net.HttpWebResponse myrp = (System.Net.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 System.IO.FileStream(filename, System.IO.FileMode.Create); long totalDownloadedByte = 0; byte[] by = new byte[1024]; int osize = st.Read(by, 0, (int)by.Length); while (osize > 0) { totalDownloadedByte = osize + totalDownloadedByte; System.Windows.Forms.Application.DoEvents(); so.Write(by, 0, osize); if (prog != null) { prog.Value = (int)totalDownloadedByte; } osize = st.Read(by, 0, (int)by.Length); percent = (float)totalDownloadedByte / (float)totalBytes * 100; label1.Text = description + "下载进度" + percent.ToString() + "%"; label1.Refresh(); System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息 System.Threading.Thread.Sleep(1); } so.Close(); st.Close(); } catch (System.Exception) { throw; } } /// <summary> /// 下载文件 /// </summary> /// <param name="URL">下载文件地址</param> /// <param name="Filename">下载后的存放地址</param> //public static void DownloadFile(string URL, string filename) // { // DownloadFile(URL, filename, null,null); // } } }
update.txt (JSON格式的文件,版本号,更新的文件等,网络和本地比对)
{ "Version":"1", "Server":"http://192.168.242.12:9001/", "Description":"修正一些Bug", "File":"Checkup.exe", "UpdateTime":"2016-06-20 12:02:05", "UpdateFiles":[ {"File":"xx.txt"}, {"File":"Checkup.exe"} ] }
AutoUpdate.cs (界面、自动更新程序。需加入Newtonsoft.Json引用,网上下载直接加入引用就可以了)
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.ComponentModel; using System.Configuration; using System.Diagnostics; using System.Threading; using System.Windows.Forms; namespace AutoUpdate { public partial class AutoUpdate : Form { private String UpdateServer ; SynchronizationContext _syncContext = null; public AutoUpdate() { InitializeComponent(); _syncContext = SynchronizationContext.Current; } private void dowm() { _syncContext.Post(downFile,new object()); } private void AutoUpdate_Load(object sender, EventArgs e) { UpdateServer = ConfigurationManager.AppSettings["UpdateServer"]; int vs = isUpdate(); if (vs == 1) { label1.Text = "正在下载更新文件,请稍候。。。"; try { new Thread(new ThreadStart(dowm)).Start(); } catch (Exception ee) { MessageBox.Show("下载异常:" + ee.Message); } } else if (vs > 1) { label1.Text = "正在下载更新文件,请稍候。。。"; try { new Thread(new ThreadStart(dowm)).Start(); //Thread.Sleep(500); //downFile(); } catch (Exception ee) { MessageBox.Show("下载异常:" + ee.Message); } } else { Console.WriteLine("小于或等于0"); this.Close(); Process.Start("Checkup.exe"); } } private int isUpdate() { //Version ApplicationVersion = new Version(Application.ProductVersion); //int version = ApplicationVersion.Major; string[] lines = System.IO.File.ReadAllLines("update.txt"); String updateFile = ""; foreach (string line in lines) { updateFile = updateFile+"\t" + line; } JObject updateJson =JObject.Parse(updateFile); int version = Int32.Parse(updateJson["Version"].ToString()); JObject udJson; try { udJson = JObject.Parse(HttpHelper.Get_Http(UpdateServer)); } catch (Exception ee) { Console.WriteLine(ee.Message); return -1; } if (udJson != null) { int serverVersion = Int32.Parse(udJson["Version"].ToString()); return serverVersion - version; // if (serverVersion-version) // { // Console.WriteLine("版本号不一致"); // return true; // } // else { // Console.WriteLine("版本一致"); // return false; // } } else { return -1; } } private void downFile1(object state) { JObject udJson = JObject.Parse(HttpHelper.Get_Http(UpdateServer)); JArray ja = (JArray)JsonConvert.DeserializeObject(udJson["UpdateFiles"].ToString()); HttpHelper.DownloadFile(udJson["Server"].ToString() + ja[ja.Count-1]["File"].ToString(), ja[ja.Count - 1]["File"].ToString(),progressBar1,label1, udJson["Description"].ToString()); HttpHelper.DownloadFile(UpdateServer, "update.txt", progressBar1, label1, udJson["Description"].ToString()); Start(); } private void downFile(object state) { JObject udJson = JObject.Parse(HttpHelper.Get_Http(UpdateServer)); JArray ja = (JArray)JsonConvert.DeserializeObject(udJson["UpdateFiles"].ToString()); for (int i = 0; i < ja.Count; i++) { HttpHelper.DownloadFile(udJson["Server"].ToString() + ja[i]["File"].ToString(), ja[i]["File"].ToString(), progressBar1, label1, udJson["Description"].ToString()); } HttpHelper.DownloadFile(UpdateServer, "update.txt", progressBar1, label1, udJson["Description"].ToString()); Start(); } private void Start() { Process.Start("Checkup.exe"); this.Hide(); this.Close(); } } }
app.config(更新地址配置文件)
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="UpdateServer" value="http://192.168.242.12:9001/update.txt"></add> </appSettings> </configuration>
需在相应的web服务器下放入版本号大于本地文件的update.txt。还有需要更新的文件。以及修改update.txt中UpdateFiles.
至此大功搞成。
源代码:http://download.csdn.net/detail/zuxuguang/9567453
以上是关于winformC# 自动更新的主要内容,如果未能解决你的问题,请参考以下文章