using ICSharpCode.SharpZipLib.Zip; using System; using System.IO; using System.Net; using System.Windows.Forms; namespace UAS_AutoUpdate { public partial class CheckUpdateWindow : Form { public static bool Zipped = false; public CheckUpdateWindow() { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; } private void CheckUpdateWindow_Load(object sender, EventArgs e) { //使用WebClient从指定位置下载文件,然后进行解压缩覆盖 WebClient wc = new WebClient(); wc.DownloadProgressChanged += Wc_DownloadProgressChanged; wc.DownloadFileAsync(new Uri("http://172.16.11.99/UAS_MES.zip"), "UAS_MES.zip"); } private void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { Action act = () => { _progressbar.Value = e.ProgressPercentage; _processrate.Text = e.ProgressPercentage + "%"; }; if (IsHandleCreated) this.Invoke(act); if (e.ProgressPercentage == 100) { if (!Zipped) { ZipHelper.UnZip(Application.StartupPath + @"\UAS_MES.zip", Application.StartupPath); } else { Close(); } } } } public class ZipHelper { /// /// 用于解压缩Zip文件 /// /// /// public static void UnZip(string ZipFilePath, string UnZipPath) { if (!File.Exists(ZipFilePath)) { throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", ZipFilePath)); } if (!Directory.Exists(UnZipPath)) { Directory.CreateDirectory(UnZipPath); } using (var s = new ZipInputStream(File.OpenRead(ZipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.IsDirectory) { continue; } string directorName = Path.Combine(UnZipPath, Path.GetDirectoryName(theEntry.Name)); string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name)); if (!Directory.Exists(directorName)) { Directory.CreateDirectory(directorName); } if (!string.IsNullOrEmpty(fileName)) { try { //防止文件正在使用中报错 using (FileStream streamWriter = File.Create(fileName)) { int size = 4096; byte[] data = new byte[size]; while (size > 0) { size = s.Read(data, 0, data.Length); streamWriter.Write(data, 0, size); } } } catch (Exception) { } } } File.Delete(Application.StartupPath + @"\UAS_MES.zip"); CheckUpdateWindow.Zipped = true; } } } }