利用第三方组件 ICSharpCode.SharpZipLib   download from:  https://github.com/icsharpcode/SharpZipLib

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Data;
  8. using System.Windows.Documents;
  9. using System.Windows.Input;
  10. using System.Windows.Media;
  11. using System.Windows.Media.Imaging;
  12. using System.Windows.Navigation;
  13. using System.Windows.Shapes;
  14. using System.Diagnostics;
  15. using System.IO;
  16. using System.ComponentModel;
  17. using ICSharpCode.SharpZipLib.Checksums;
  18. using ICSharpCode.SharpZipLib.Zip;
  19.  
  20. namespace OnlineUpdate
  21. {
  22. /// <summary>
  23. /// Interaction logic for MainWindow.xaml
  24. /// </summary>
  25. public partial class MainWindow : Window
  26. {
  27. public MainWindow()
  28. {
  29. InitializeComponent();
  30. String[] arguments = Environment.GetCommandLineArgs();
  31. bool valid = false;
  32. foreach (string s in arguments)
  33. { //arguments =update|serverUrl|mainAPP
  34. if (s.StartsWith ( "update|"))
  35. {
  36. serverUrl = s.Split ('|')[1].Trim() ;
  37. mainAPP = s.Split('|')[2].Trim();
  38. valid = true;
  39. }
  40. }
  41. if (!valid)
  42. {
  43. Application.Current.Shutdown();
  44.  
  45. }
  46. worker = new BackgroundWorker();
  47. worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); ;
  48. worker.DoWork += new DoWorkEventHandler(worker_DoWork);
  49. Loaded += new RoutedEventHandler(MainWindow_Loaded);
  50.  
  51. }
  52.  
  53. string AppFolder = AppDomain.CurrentDomain.BaseDirectory;
  54. string mainAPP = "xx.exe";
  55. string serverUrl = "";
  56. BackgroundWorker worker;
  57. bool isDownloadOK = false;
  58. void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  59. {
  60. if (isDownloadOK)
  61. {
  62. copyFiles();
  63. }
  64. }
  65.  
  66. void worker_DoWork(object sender, DoWorkEventArgs e)
  67. {
  68. dowloadFile();
  69. }
  70.  
  71. private static string UpdateZipFile = "Update.rar";
  72.  
  73. void MainWindow_Loaded(object sender, RoutedEventArgs e)
  74. {
  75.  
  76. int tryCont=0;
  77. closedMainApp();
  78. while (!checkHasClosedMainApp())
  79. {
  80. tryCont++;
  81. MessageBox.Show("请关闭["+mainAPP.Replace(".exe","")+"]再试!" );
  82. if(tryCont>3){
  83. MessageBox.Show("无法关闭" + mainAPP.Replace(".exe", "") + ".无法继续更新");
  84. Application.Current.Shutdown();
  85. break ;
  86. }
  87.  
  88. }
  89.  
  90. Show();
  91. //start download update
  92. worker.RunWorkerAsync();
  93.  
  94. }
  95.  
  96. void dowloadFile()
  97. {
  98. isDownloadOK = false;
  99. string StrFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, UpdateZipFile);
  100. // string serverUrl = "http://files.cnblogs.com/files/pcat/hackbar.zip";//"https://files.cnblogs.com/files/wgscd/jyzsUpdate.zip"; //根据实际情况设置
  101. System.IO.FileStream fs;
  102. fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
  103. try
  104. {
  105. System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(serverUrl);
  106. System.Net.WebResponse response = request.GetResponse();
  107. System.IO.Stream ns = response.GetResponseStream();
  108. long totalSize = response.ContentLength;
  109. long hasDownSize = 0;
  110. byte[] nbytes = new byte[512];//521,2048 etc
  111. int nReadSize = 0;
  112. nReadSize = ns.Read(nbytes, 0, nbytes.Length);
  113. while (nReadSize > 0)
  114. {
  115. fs.Write(nbytes, 0, nReadSize);
  116. nReadSize = ns.Read(nbytes, 0, 512);
  117. hasDownSize += nReadSize;
  118. Dispatcher.BeginInvoke(new Action(() =>
  119. {
  120. txt.Text = "" + hasDownSize + "/" + totalSize + " (" + (((double)hasDownSize * 100 / totalSize).ToString("0")) + "%)";//显示下载百分比
  121. lbPercent.Width = gridPercent.RenderSize.Width * ((double)hasDownSize / totalSize);
  122. txt.UpdateLayout();//DoEvents();
  123. }));
  124.  
  125. }
  126. Dispatcher.BeginInvoke(new Action(() =>
  127. {
  128. txt.Text = "100%";//显示下载百分比
  129. txt.UpdateLayout();//DoEvents();
  130. }));
  131.  
  132. fs.Close();
  133. ns.Close();
  134. isDownloadOK = true;
  135. // MessageBox.Show("下载完成");
  136. }
  137. catch (Exception ex)
  138. {
  139. fs.Close();
  140. MessageBox.Show("出现错误:" + ex.ToString());
  141. }
  142. }
  143.  
  144. void copyFiles() {
  145. try
  146. {
  147. txt.Text = "正在复制解压文件......";
  148. txt2.Visibility = System.Windows.Visibility.Collapsed;
  149. gridPercent.Visibility = System.Windows.Visibility.Collapsed;
  150. UnZip(UpdateZipFile, AppFolder, "", true);
  151. txt.Text = "更新完成!";
  152. txt.FontSize = 55;
  153. txt.Foreground = new SolidColorBrush(Colors.Green);
  154. MessageBox.Show("恭喜更新完成!");
  155. string mainApp = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, mainAPP);
  156. System.Diagnostics.Process.Start(mainApp);
  157. Application.Current.Shutdown();
  158. }
  159. catch(Exception ex) {
  160.  
  161. MessageBox.Show("更新出错:\r\n"+ex.Message );
  162. Application.Current.Shutdown();
  163. }
  164.  
  165. }
  166.  
  167. /// <summary>
  168. /// ZIP:解压一个zip文件
  169. /// add yuangang by 2016-06-13
  170. /// </summary>
  171. /// <param name="ZipFile">需要解压的Zip文件(绝对路径)</param>
  172. /// <param name="TargetDirectory">解压到的目录</param>
  173. /// <param name="Password">解压密码</param>
  174. /// <param name="OverWrite">是否覆盖已存在的文件</param>
  175. public static void UnZip(string ZipFile, string TargetDirectory, string Password, bool OverWrite = true)
  176. {
  177. //如果解压到的目录不存在,则报错
  178. if (!System.IO.Directory.Exists(TargetDirectory))
  179. {
  180. System.IO.Directory.CreateDirectory(TargetDirectory);
  181. //throw new System.IO.FileNotFoundException("指定的目录: " + TargetDirectory + " 不存在!");
  182. }
  183.  
  184. //目录结尾
  185. if (!TargetDirectory.EndsWith("\\")) { TargetDirectory = TargetDirectory + "\\"; }
  186.  
  187. using (ZipInputStream zipfiles = new ZipInputStream(File.OpenRead(ZipFile)))
  188. {
  189. zipfiles.Password = Password;
  190. ZipEntry theEntry;
  191.  
  192. while ((theEntry = zipfiles.GetNextEntry()) != null)
  193. {
  194. string directoryName = "";
  195. string pathToZip = "";
  196. pathToZip = theEntry.Name;
  197.  
  198. if (pathToZip != "")
  199. directoryName = System.IO.Path.GetDirectoryName(pathToZip) + "\\";
  200.  
  201. string fileName = System.IO.Path.GetFileName(pathToZip);
  202. Directory.CreateDirectory(TargetDirectory + directoryName);
  203. if (fileName != "")
  204. {
  205. if ((File.Exists(TargetDirectory + directoryName + fileName) && OverWrite) || (!File.Exists(TargetDirectory + directoryName + fileName)))
  206. {
  207. using (FileStream streamWriter = File.Create(TargetDirectory + directoryName + fileName))
  208. {
  209. int size = 2048;
  210. byte[] data = new byte[2048];
  211. while (true)
  212. {
  213. size = zipfiles.Read(data, 0, data.Length);
  214.  
  215. if (size > 0)
  216. streamWriter.Write(data, 0, size);
  217. else
  218. break;
  219. }
  220. streamWriter.Close();
  221. }
  222. }
  223. }
  224. }
  225.  
  226. zipfiles.Close();
  227. }
  228. }
  229.  
  230. /// <summary>
  231. /// 断点续传
  232. /// </summary>
  233. void dowloadFileWithCache()
  234. {
  235. string StrFileName = "d:\\wgscd2.zip"; //根据实际情况设置
  236. string StrUrl = "http://files.cnblogs.com/files/pcat/hackbar.zip";//"https://files.cnblogs.com/files/wgscd/xxx.zip"; //根据实际情况设置
  237. //打开上次下载的文件或新建文件
  238. long lStartPos = 0;
  239. System.IO.FileStream fs;
  240. if (System.IO.File.Exists(StrFileName))//另外如果文件已经下载完毕,就不需要再断点续传了,不然请求的range 会不合法会抛出异常。
  241. {
  242. fs = System.IO.File.OpenWrite(StrFileName);
  243. lStartPos = fs.Length;
  244. fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
  245. }
  246. else
  247. {
  248. fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
  249. lStartPos = 0;
  250. }
  251. //打开网络连接
  252. try
  253. {
  254. System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
  255. if (lStartPos > 0)
  256. {
  257. request.AddRange((int)lStartPos); //设置Range值
  258. }
  259. System.Net.WebResponse response = request.GetResponse();
  260. //向服务器请求,获得服务器回应数据流
  261. System.IO.Stream ns = response.GetResponseStream();
  262. long totalSize = response.ContentLength;
  263. long hasDownSize = 0;
  264. byte[] nbytes = new byte[512];//521,2048 etc
  265. int nReadSize = 0;
  266. nReadSize = ns.Read(nbytes, 0, nbytes.Length);
  267. while (nReadSize > 0)
  268. {
  269. fs.Write(nbytes, 0, nReadSize);
  270. nReadSize = ns.Read(nbytes, 0, 512);
  271. hasDownSize += nReadSize;
  272. txt.Text = "" + hasDownSize + "/" + totalSize + " (" + (((double)hasDownSize * 100 / totalSize).ToString("0.00")) + "%)";//显示下载百分比
  273. txt.UpdateLayout();//DoEvents();
  274. }
  275. fs.Close();
  276. ns.Close();
  277. MessageBox.Show("下载完成");
  278. }
  279. catch (Exception ex)
  280. {
  281. fs.Close();
  282. MessageBox.Show("下载过程中出现错误:" + ex.ToString());
  283. }
  284. }
  285.  
  286. bool checkHasClosedMainApp()
  287. {
  288.  
  289. string path = "";
  290.  
  291. Process[] ps = Process.GetProcessesByName(mainAPP.Replace(".exe",""));
  292. //string n= Process.GetCurrentProcess().MainModule.FileName;
  293. foreach (Process p in ps)
  294. {
  295. path = p.MainModule.FileName.ToString();
  296. return false;
  297. }
  298.  
  299. return true;
  300. }
  301.  
  302. void closedMainApp()
  303. {
  304.  
  305. string path = "";
  306.  
  307. Process[] ps = Process.GetProcessesByName(mainAPP.Replace(".exe", ""));
  308. //string n= Process.GetCurrentProcess().MainModule.FileName;
  309. foreach (Process p in ps)
  310. {
  311. path = p.MainModule.FileName.ToString();
  312. p.CloseMainWindow();
  313. System.Threading.Thread.Sleep(1000);
  314.  
  315. }
  316.  
  317. }
  318.  
  319. }
  320. }

  

C# zip -ICSharpCode.SharpZipLib的更多相关文章

  1. zip (ICSharpCode.SharpZipLib.dll文件需要下载)

    ZipClass zc=new ZipClass (); zc.ZipDir(@"E:\1\新建文件夹", @"E:\1\新建文件夹.zip", 1);//压缩 ...

  2. 使用NPOI读取Excel报错ICSharpCode.SharpZipLib.Zip.ZipException:Wrong Local header signature

    写了一个小程序利用NPOI来读取Excel,弹出这样的报错: ICSharpCode.SharpZipLib.Zip.ZipException:Wrong Local header signature ...

  3. C#调用 ICSharpCode.SharpZipLib.Zip 实现解压缩功能公用类

    最近想用个解压缩功能 从网上找了找 加自己修改,个人感觉还是比较好用的,直接上代码如下 using System; using System.Linq; using System.IO; using ...

  4. ICSharpCode.SharpZipLib.dll,MyZip.dll,Ionic.Zip.dll 使用

    MyZip.dll : 有BUG,会把子目录的文件解压到根目录.. ICSharpCode.SharpZipLib.dll: 把ICSharpCode.SharpZipLib.dll复制一份,重命名为 ...

  5. 利用ICSharpCode.SharpZipLib.Zip进行文件压缩

    官网http://www.icsharpcode.net/ 支持文件和字符压缩. 创建全新的压缩包 第一步,创建压缩包 using ICSharpCode.SharpZipLib.Zip; ZipOu ...

  6. C# zip/unzip with ICSharpCode.SharpZipLib

    download ICSharpCode and add reference using System; using System.Collections.Generic; using System. ...

  7. 使用ICSharpCode.SharpZipLib.Zip实现压缩与解压缩

    使用开源类库ICSharpCode.SharpZipLib.Zip可以实现压缩与解压缩功能,源代码和DLL可以从http://www.icsharpcode.net/OpenSource/SharpZ ...

  8. ICSharpCode.SharpZipLib.Zip

    //压缩整个目录下载 var projectFolder = Request.Params["folder"] != null ? Request.Params["fol ...

  9. 基于ICSharpCode.SharpZipLib.Zip的压缩解压缩

    原文:基于ICSharpCode.SharpZipLib.Zip的压缩解压缩 今天记压缩解压缩的使用,是基于开源项目ICSharpCode.SharpZipLib.Zip的使用. 一.压缩: /// ...

随机推荐

  1. Android为TV端助力 doc里面adb连接出现问题的解决方法

    第一保证连接的两边都是有网的 第二  就是网上常说的1.adb kill-server 2.adb start-server 3.adb remount 但是在运行adb remount有可能会提示 ...

  2. Django+MongoDB批量插入数据

    在百万级和千万级数据级别进行插入,pymongo的insert_many()方法有着很强的优势.原因是每次使用insert_one()方法进行插入数据,都是要对数据库服务器进行一次访问,而这样的访问是 ...

  3. swipe使用及竖屏页面滚动方法

    基于swipe4写了一个移动端的全屏滚动效果  但是图片始终不能自适应屏幕设备大小  这里记录一下 开始的时候要设置  移动端配置 <meta name="viewport" ...

  4. 自动化测试基础篇--Selenium获取元素属性

    摘自https://www.cnblogs.com/sanzangTst/p/8375938.html 通常在做断言之前,都要先获取界面上元素的属性,然后与期望结果对比. 一.获取页面title 二. ...

  5. 初识kafka

    简介     Kafka经常用于实时流数据架构,用于提供实时分析.本篇将会简单介绍kafka以及它为什么能够广泛应用. kafka的增长是爆炸性的.2017年超过三分之一的世界五百强公司在使用kafk ...

  6. Lua无法排序的问题(Key需要是连续的)

    排序的Key需要是连续的 local x = {[1]={x=6}, [2]={x=5}, [3]={x=7}, [5]={x=2}, [6]={x=8}, [7]={x=5}} ---从小到大排序 ...

  7. live555源码学习1---Socket流程架构图

    怎么说呢,换了工作环境,好多软件公司禁止使用了,有道笔记也无法使用了.发现博客园还可以上传图片,以后只能在这里记录了. 越发的感觉需要尽快把live555的代码拿下.因为工作环境问题,webrtc的源 ...

  8. Git&GitHub语法大全

    目录 1. GitHub与Git万用语法 1)创建库 2)添加和提交到仓库 3)版本回退 4)缓存区和暂存区 5)撤销和删除文件 6)远程仓库 7)创建和合并分支 2. 更多Git语法 1. GitH ...

  9. 力扣算法题—051N皇后问题

    #include "000库函数.h" //使用回溯法来计算 //经典解法为回溯递归,一层一层的向下扫描,需要用到一个pos数组, //其中pos[i]表示第i行皇后的位置,初始化 ...

  10. Java数据结构简述

    1.数组 概念:一个存储元素的线性集合. 数组声明和创建: dataType[] arrayRefVar = new dataType[arraySize]; 二维数组(多维数组)声明和创建: dat ...