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)
{
if (s == "update")
{
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); }
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("please close main app");
if(tryCont>3){
MessageBox.Show("can not do update ,need close main app");
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 StrUrl = "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(StrUrl);
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() { txt.Text = "正在复制解压文件......";
txt2.Visibility = System.Windows.Visibility.Collapsed;
gridPercent.Visibility = System.Windows.Visibility.Collapsed;
UnZip(UpdateZipFile, AppDomain.CurrentDomain.BaseDirectory, "");
txt.Text = "更新完成!";
txt. FontSize = 55;
txt.Foreground = new SolidColorBrush(Colors.Green);
MessageBox.Show("update Ok, now new version will start");
string mainApp = AppDomain.CurrentDomain.BaseDirectory + "\\JiayuanTool.exe";
System.Diagnostics.Process.Start(mainApp);
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("JiayuanTool");
//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("JiayuanTool");
//string n= Process.GetCurrentProcess().MainModule.FileName;
foreach (Process p in ps)
{
path = p.MainModule.FileName.ToString();
p.CloseMainWindow();
System.Threading.Thread.Sleep(1000); } } }
}

  

UI :

<Window x:Class="OnlineUpdate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Name="txt" HorizontalAlignment="Center" FontSize="22" VerticalAlignment="Center" Margin="12,-42,0,0">000/0000</TextBlock>
<Grid Name="gridPercent" Background="WhiteSmoke" VerticalAlignment="Center" Margin="12,22,0,0">
<Label Name="lbPercent" Background="Green" Width="0" HorizontalAlignment="Left"></Label>
</Grid>
<Label Name="txt2" Foreground="Green" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,80,0,0">正在下载更新...</Label> </Grid>
</Window>

  

C# online update demo的更多相关文章

  1. MyBatis注解-动态SQL 一个 SqlProvider的demo

    Provider动态语言注解 MyBatis提供了多个注解如:@InsertProvider,@UpdateProvider,@DeleteProvider和@SelectProvider,这些都是建 ...

  2. 通用dao的demo

          代码片段 1. [代码]整型映射工具 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package org.dave.common.databas ...

  3. JQuery 滚动条插件perfect-scrollbar

    原文地址 https://github.com/noraesae/perfect-scrollbar perfect-scrollbar Tiny but perfect jQuery scrollb ...

  4. .NET 开源SqlServer ORM框架 SqlSugar 3.0 API

    3.1.x ,将作为3.X系统的最后一个版本,下面将会开发 全新的功能 更新列表:https://github.com/sunkaixuan/SqlSugar/releases 优点: SqlSuga ...

  5. PL/SQL通过存储过程为相同数据添加序号

    在Oracle数据库中存有一串数据(Ori_Seq),数据包含不等量重复: 为方便查看与管理,现希望添加一字段(New_Seq),在原有数据的末尾为其添加一串序号,相同数据序号从小到大排列,序号长度为 ...

  6. Asp.net Core的代码移植技巧,半天将SqlSugarORM转成Core

    .net  core中有哪些被抛弃的类 1.DataTable DataRow SqlDataAdapter DataRow DataColumn DataColumn 虽然这些类不是我ORM核心功能 ...

  7. oracle 10g编程

    一.概述 1.sql语言特点 sql语言采用集合操作方式,对数据的处理是成组进行的,而不是一条一条处理,听过使用集合操作方式,可以家加快数据的处理速度. 执行sql语句时每次只能发送并处理一条语句.如 ...

  8. [CoreOS 转载] CoreOS实践指南(五):分布式数据存储Etcd(上)

    转载:http://www.csdn.net/article/2015-01-22/2823659 摘要:在“漫步云端:CoreOS实践指南”系列的前几篇,分别介绍了如何架设CoreOS集群,系统服务 ...

  9. Javascript高性能动画与页面渲染

    转自:http://www.infoq.com/cn/articles/javascript-high-performance-animation-and-page-rendering No setT ...

随机推荐

  1. SD配置步骤清单

    定义销售组织 定义分销渠道 定义产品组 给公司代码分配销售组织 给销售组织分配销售渠道 给工厂分配销售组织.分销渠道 给销售组织分配产品组 定义销售范围 定义装运点 给工厂分配装运点 维护工厂的装运点 ...

  2. Postman Postman测试接口之JSON结构化数据提交

    Postman测试接口之JSON结构化数据提交   by:授客 QQ:1033553122 本文主要是针对结构比较复杂一点的JSON协议数据的提交做个简单说明 举例: 用户下订单接口 接口方向 客户端 ...

  3. Visual Studio Code必备插件

    HTML Snippets: 超级实用且初级的 H5代码片段以及提示 HTMLHint: html代码检测 HTML CSS Support : 让 html 标签上写class 智能提示当前项目所支 ...

  4. JUnit手动设计测试方法以及与Randoop的自动生成测试的比较

    手动设计测试 在已有的web project本地目录lib文件夹里导入两个jar文件(版本可不一样):junit-4.12.jar和hamcrest.jar 打开eclipse,导入项目,右击项目选择 ...

  5. FragmentStatePagerAdapter和FragmentPagerAdapter区别

    FragmentPageAdapter和FragmentStatePagerAdapter 我们简要的来分析下这两个Adapter的区别: FragmentPageAdapter:和PagerAdap ...

  6. Android系统常用的adb命令

    自己工作中经常要用一些Android的adb命令,把常用的adb命令记录一下,留作备忘. adb devices 查看当前连接的设备 adb install 安装 adb install拖动apk到命 ...

  7. c# 子窗体打开或者切换就最大化

    “用MDI方式打开一个子窗口体后,总是不能最大化显示,明明子窗口体的WindowState设置为Maximized?”,相信有很多人会遇到这的样问题,请按下面的方法设置即可使MDI子窗体最大化:1.把 ...

  8. CSS盒模型详解(图文教程)

    本文最初发表于博客园,并在GitHub上持续更新.以下是正文. 盒子模型 前言 盒子模型,英文即box model.无论是div.span.还是a都是盒子. 但是,图片.表单元素一律看作是文本,它们并 ...

  9. 使用anaconda安装pytorch的清华镜像地址

    1.安装anaconda:国内镜像网址:https://mirror.tuna.tsinghua.edu.cn/help/anaconda/下载对应系统对应python版本的anaconda版本(Li ...

  10. Linux基础知识与基础命令

    Linux基础知识与基础命令 系统目录 Linux只有一个根目录,没有盘符的概念,文件目录是一个倒立的树形结构. 常用的目录功能 bin 与程序相关的文件 boot 与系统启动相关 cdrom 与Li ...