文档章节

C# online update demo

o
 osc_4nmshwhm
发布于 2018/08/06 17:39
字数 907
阅读 0
收藏 0

精选30+云产品,助力企业轻松上云!>>>

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>

  

 

o
粉丝 0
博文 500
码字总数 0
作品 0
私信 提问
加载中
请先登录后再评论。

暂无文章

平时使用的Lszrz到底是什么协议?说说Xmodem/Ymodem/Zmodem

XMODEM, YMODEM, and ZMODEM 由于平时使用rz/sz较多,r/s好理解,一个send一个receive。但是由不太清楚z是什么意思,故有此文。 sx/rx, sb/rb (b=batch)和sz/rz分别实现了xmodem,ymodem和z...

独钓渔
36分钟前
17
0
真正的强智能时代已经到来。道翰天琼认知智能机器人平台API大脑。

最近,我常说人工智能的寒冬快要来了,提醒业界要做好思想准备,但同时我也说:冬天来了,春天就不会远了…… 2019年6月我写了篇文章《深度学习的问题究竟在哪?》,说到深度学习的一个主要问...

jackli2020
45分钟前
24
0
什么是控制型人格,控制型人格的筛查测试

一、 什么是控制性人格 拥有控制型人格的人,他们会尽力的隐藏自己的意图,但是又会使用很微妙的方式来利用周围人的弱点,进而占取便宜时,使他们能够得到自己想要的东西。这类人的控制欲非常...

蛤蟆丸子
54分钟前
14
0
【Spring】Spring AOP 代理对象生成逻辑源码分析

1. spring aop案例(POJO注入) 1.0 被代理接口 TargetInterface /** * 被代理的接口 * @author Yang ZhiWei */public interface TargetInterface { void show(); String show......

ZeroneLove
今天
36
0
聊聊dubbo-go的gracefulShutdownFilter

序 本文主要研究一下dubbo-go的gracefulShutdownFilter gracefulShutdownFilter dubbo-go-v1.4.2/filter/filter_impl/graceful_shutdown_filter.go type gracefulShutdownFilter struct {......

go4it
今天
30
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部