標籤:
感覺用的到,存下來,轉自:http://blog.csdn.net/gisfarmer/article/details/4437994
現在但凡是一個程式都有相應的升級程式,如果你的程式沒有相應的升級程式,那麼你就需要留意了。你的使用者很可能丟失!!!網上關於自動升級的例子也有很多,前幾天一個朋友很苦惱的跟我說它的客戶在逐漸減少(據他所說,他都客戶因為他的程式升級很麻煩,所以很多人放棄了使用它的軟體),問我說怎麼辦?其實他也知道該怎麼辦?所以...朋友嘛!就給他做了一個自動升級程式。恰好今天CSDN上的一位老友也詢問這件事情,所以就把代碼共用大家了。
先個幾個圖:
主要原理(相當簡單):
升級程式一定要是一個單獨的exe,最好不要和你的程式綁到一起(否則升級程式無法啟動)。主程式退出----升級程式啟動----升級程式訪問你的網站的升級設定檔-----讀取設定檔裡面資訊-----下載-----升級程式關閉----主程式啟動
主要代碼:
1.讀取設定檔:
1 private void GetUpdateInfo() 2 { 3 //擷取伺服器資訊 4 WebClient client = new WebClient(); 5 doc = new XmlDocument(); 6 try 7 { 8 doc.Load(client.OpenRead("http://192.168.3.43/update/update.xml")); 9 //doc.Load(client.OpenRead(Config.IniReadValue("Update","UpdateURL",Application.StartupPath+"//config.ini")+"//update.xml"));10 //doc.Load(Application.StartupPath + "//update.xml");11 client = null;12 }13 catch14 {15 this.labHtml.Text = "無法取得更新檔案!程式升級失敗!";16 return;17 }18 if (doc == null)19 return;20 //分析檔案21 XmlNode node;22 //擷取檔案清單23 string RootPath = doc.SelectSingleNode("Product/FileRootPath").InnerText.Trim();24 node = doc.SelectSingleNode("Product/FileList");25 if (node != null)26 {27 foreach (XmlNode xn in node.ChildNodes)28 {29 this.listView1.Items.Add(new ListViewItem(new string[]30 {31 xn.Attributes["Name"].Value.ToString(), 32 new WebFileInfo(RootPath+xn.Attributes["Name"].Value.ToString()).GetFileSize().ToString(),33 "---"34 }));35 }36 }37 }
2.檔案下載:
/// <summary> /// 下載檔案 /// </summary> public void Download() { FileStream fs = new FileStream( this.strFile,FileMode.Create,FileAccess.Write,FileShare.ReadWrite ); try { this.objWebRequest = (HttpWebRequest)WebRequest.Create( this.strUrl ); this.objWebRequest.AllowAutoRedirect = true;// int nOffset = 0; long nCount = 0; byte[] buffer = new byte[ 4096 ]; //4KB int nRecv = 0; //接收到的位元組數 this.objWebResponse = (HttpWebResponse)this.objWebRequest.GetResponse(); Stream recvStream = this.objWebResponse.GetResponseStream(); long nMaxLength = (int)this.objWebResponse.ContentLength; if( this.bCheckFileSize && nMaxLength != this.nFileSize ) { throw new Exception( string.Format( "檔案/"{0}/"被損壞,無法下載!",Path.GetFileName( this.strFile ) ) ); } if( this.DownloadFileStart != null ) this.DownloadFileStart( new DownloadFileStartEventArgs( (int)nMaxLength ) ); while( true ) { nRecv = recvStream.Read( buffer,0,buffer.Length ); if( nRecv == 0 ) break; fs.Write( buffer,0,nRecv ); nCount += nRecv; //引發下載塊完成事件 if( this.DownloadFileBlock != null ) this.DownloadFileBlock( new DownloadFileEventArgs( (int)nMaxLength,(int)nCount ) ); } recvStream.Close(); //引發下載完成事件 if( this.DownloadFileComplete != null ) this.DownloadFileComplete( this,EventArgs.Empty ); } finally { fs.Close(); } }
C# 編寫自動更新程式 (轉)