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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip; namespace OnlineUpdate
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
String[] arguments = Environment.GetCommandLineArgs();
bool valid = false;
foreach (string s in arguments)
{ //arguments =update|serverUrl|mainAPP
if (s.StartsWith ( "update|"))
{
serverUrl = s.Split ('|')[1].Trim() ;
mainAPP = s.Split('|')[2].Trim();
valid = true;
}
}
if (!valid)
{
Application.Current.Shutdown(); }
worker = new BackgroundWorker();
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted); ;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
Loaded += new RoutedEventHandler(MainWindow_Loaded); } string AppFolder = AppDomain.CurrentDomain.BaseDirectory;
string mainAPP = "xx.exe";
string serverUrl = "";
BackgroundWorker worker;
bool isDownloadOK = false;
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (isDownloadOK)
{
copyFiles();
}
} void worker_DoWork(object sender, DoWorkEventArgs e)
{
dowloadFile();
} private static string UpdateZipFile = "Update.rar"; void MainWindow_Loaded(object sender, RoutedEventArgs e)
{ int tryCont=0;
closedMainApp();
while (!checkHasClosedMainApp())
{
tryCont++;
MessageBox.Show("请关闭["+mainAPP.Replace(".exe","")+"]再试!" );
if(tryCont>3){
MessageBox.Show("无法关闭" + mainAPP.Replace(".exe", "") + ".无法继续更新");
Application.Current.Shutdown();
break ;
} } Show();
//start download update
worker.RunWorkerAsync(); } void dowloadFile()
{
isDownloadOK = false;
string StrFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, UpdateZipFile);
// string serverUrl = "http://files.cnblogs.com/files/pcat/hackbar.zip";//"https://files.cnblogs.com/files/wgscd/jyzsUpdate.zip"; //根据实际情况设置
System.IO.FileStream fs;
fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(serverUrl);
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream ns = response.GetResponseStream();
long totalSize = response.ContentLength;
long hasDownSize = 0;
byte[] nbytes = new byte[512];//521,2048 etc
int nReadSize = 0;
nReadSize = ns.Read(nbytes, 0, nbytes.Length);
while (nReadSize > 0)
{
fs.Write(nbytes, 0, nReadSize);
nReadSize = ns.Read(nbytes, 0, 512);
hasDownSize += nReadSize;
Dispatcher.BeginInvoke(new Action(() =>
{
txt.Text = "" + hasDownSize + "/" + totalSize + " (" + (((double)hasDownSize * 100 / totalSize).ToString("0")) + "%)";//显示下载百分比
lbPercent.Width = gridPercent.RenderSize.Width * ((double)hasDownSize / totalSize);
txt.UpdateLayout();//DoEvents();
})); }
Dispatcher.BeginInvoke(new Action(() =>
{
txt.Text = "100%";//显示下载百分比
txt.UpdateLayout();//DoEvents();
})); fs.Close();
ns.Close();
isDownloadOK = true;
// MessageBox.Show("下载完成");
}
catch (Exception ex)
{
fs.Close();
MessageBox.Show("出现错误:" + ex.ToString());
}
} void copyFiles() {
try
{
txt.Text = "正在复制解压文件......";
txt2.Visibility = System.Windows.Visibility.Collapsed;
gridPercent.Visibility = System.Windows.Visibility.Collapsed;
UnZip(UpdateZipFile, AppFolder, "", true);
txt.Text = "更新完成!";
txt.FontSize = 55;
txt.Foreground = new SolidColorBrush(Colors.Green);
MessageBox.Show("恭喜更新完成!");
string mainApp = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, mainAPP);
System.Diagnostics.Process.Start(mainApp);
Application.Current.Shutdown();
}
catch(Exception ex) { MessageBox.Show("更新出错:\r\n"+ex.Message );
Application.Current.Shutdown();
} } /// <summary>
/// ZIP:解压一个zip文件
/// add yuangang by 2016-06-13
/// </summary>
/// <param name="ZipFile">需要解压的Zip文件(绝对路径)</param>
/// <param name="TargetDirectory">解压到的目录</param>
/// <param name="Password">解压密码</param>
/// <param name="OverWrite">是否覆盖已存在的文件</param>
public static void UnZip(string ZipFile, string TargetDirectory, string Password, bool OverWrite = true)
{
//如果解压到的目录不存在,则报错
if (!System.IO.Directory.Exists(TargetDirectory))
{
System.IO.Directory.CreateDirectory(TargetDirectory);
//throw new System.IO.FileNotFoundException("指定的目录: " + TargetDirectory + " 不存在!");
} //目录结尾
if (!TargetDirectory.EndsWith("\\")) { TargetDirectory = TargetDirectory + "\\"; } using (ZipInputStream zipfiles = new ZipInputStream(File.OpenRead(ZipFile)))
{
zipfiles.Password = Password;
ZipEntry theEntry; while ((theEntry = zipfiles.GetNextEntry()) != null)
{
string directoryName = "";
string pathToZip = "";
pathToZip = theEntry.Name; if (pathToZip != "")
directoryName = System.IO.Path.GetDirectoryName(pathToZip) + "\\"; string fileName = System.IO.Path.GetFileName(pathToZip);
Directory.CreateDirectory(TargetDirectory + directoryName);
if (fileName != "")
{
if ((File.Exists(TargetDirectory + directoryName + fileName) && OverWrite) || (!File.Exists(TargetDirectory + directoryName + fileName)))
{
using (FileStream streamWriter = File.Create(TargetDirectory + directoryName + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = zipfiles.Read(data, 0, data.Length); if (size > 0)
streamWriter.Write(data, 0, size);
else
break;
}
streamWriter.Close();
}
}
}
} zipfiles.Close();
}
} /// <summary>
/// 断点续传
/// </summary>
void dowloadFileWithCache()
{
string StrFileName = "d:\\wgscd2.zip"; //根据实际情况设置
string StrUrl = "http://files.cnblogs.com/files/pcat/hackbar.zip";//"https://files.cnblogs.com/files/wgscd/xxx.zip"; //根据实际情况设置
//打开上次下载的文件或新建文件
long lStartPos = 0;
System.IO.FileStream fs;
if (System.IO.File.Exists(StrFileName))//另外如果文件已经下载完毕,就不需要再断点续传了,不然请求的range 会不合法会抛出异常。
{
fs = System.IO.File.OpenWrite(StrFileName);
lStartPos = fs.Length;
fs.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
}
else
{
fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
lStartPos = 0;
}
//打开网络连接
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
if (lStartPos > 0)
{
request.AddRange((int)lStartPos); //设置Range值
}
System.Net.WebResponse response = request.GetResponse();
//向服务器请求,获得服务器回应数据流
System.IO.Stream ns = response.GetResponseStream();
long totalSize = response.ContentLength;
long hasDownSize = 0;
byte[] nbytes = new byte[512];//521,2048 etc
int nReadSize = 0;
nReadSize = ns.Read(nbytes, 0, nbytes.Length);
while (nReadSize > 0)
{
fs.Write(nbytes, 0, nReadSize);
nReadSize = ns.Read(nbytes, 0, 512);
hasDownSize += nReadSize;
txt.Text = "" + hasDownSize + "/" + totalSize + " (" + (((double)hasDownSize * 100 / totalSize).ToString("0.00")) + "%)";//显示下载百分比
txt.UpdateLayout();//DoEvents();
}
fs.Close();
ns.Close();
MessageBox.Show("下载完成");
}
catch (Exception ex)
{
fs.Close();
MessageBox.Show("下载过程中出现错误:" + ex.ToString());
}
} bool checkHasClosedMainApp()
{ string path = ""; Process[] ps = Process.GetProcessesByName(mainAPP.Replace(".exe",""));
//string n= Process.GetCurrentProcess().MainModule.FileName;
foreach (Process p in ps)
{
path = p.MainModule.FileName.ToString();
return false;
} return true;
} void closedMainApp()
{ string path = ""; Process[] ps = Process.GetProcessesByName(mainAPP.Replace(".exe", ""));
//string n= Process.GetCurrentProcess().MainModule.FileName;
foreach (Process p in ps)
{
path = p.MainModule.FileName.ToString();
p.CloseMainWindow();
System.Threading.Thread.Sleep(1000); } } }
}

  

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. 14.Odoo产品分析 (二) – 商业板块(7) –制造(1)

    查看Odoo产品分析系列--目录 一旦你收到了库存中所需的原材料,就可以开始生产终端产品了.ERP系统的部分功能是帮助您根据可用资源调度这些订单.其中一项资源是原产品.其他资源可以包括可用劳动力或特定 ...

  2. iOS----------SVN问题 the operation could not be completed

    可能是服务器磁盘满了或者你本地的内存满了

  3. 深入理解Java虚拟机01--概述

    本课题是对<深入理解Java虚拟机>周志明 第二版的总结   具体可以参考:https://pan.baidu.com/s/1v_mPp--XV4u4rCBMkbR37A 第1版 可以忽略 ...

  4. springboot 学习之路 7(静态页面自动生效问题)

    目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...

  5. YourSQLDba遭遇.NET Framework Error 6522

    一工厂的SQL Server数据库服务器上的YourSQLDba_LogBackups作业做事务日志备份时,突然出现异常,异常的错误信息指向.NET Framework,出现这个问题时,一般我估计是该 ...

  6. bootstrap-paginator分页示例 源码 MVC

    准备 1.数据:bootstrap包(含分页插件bootstrap-paginator.js) 2.技术方案:ajax动态加载分页.部分视图.BLL取数 代码 模板页 @{ Layout = null ...

  7. Big Endian  和 Little Endian 模式的区别

    谈到字节序的问题,必然牵涉到两大CPU派系.那就是Motorola的PowerPC系列CPU和Intel的x86系列CPU.PowerPC系列采用big endian方式存储数据,而x86系列则采用l ...

  8. HTTP与TCP的区别和联系

    工作原理(转载): https://www.cnblogs.com/zimohul/p/6506406.html 相信不少初学手机联网开发的朋友都想知道Http与Socket连接究竟有什么区别,希望通 ...

  9. 【Teradata】并行操作工具

    1.psh并行shell //单机模式 psh date psh pdestate -a psh verify_pdisks //交互模式 psh psh.>help psh.>selec ...

  10. node基础—global对象(全局对象)

    global对象的__filename属性和__dirname属性 __filename属性:返回当前执行的文件的文件路径,该路径是经过解析后的绝对路径,在模块中,该路径是模块文件的路径,此属性并非全 ...