【1】下载文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace XuanWu.Software.EasyInfo.Interface.Update
{
    public class DownloadThread
    {
        #region DownLoadOneFile(下载单个文件)
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="filePath">保存路径</param>
        /// <returns></returns>
        public bool DownLoadOneFile(string url, string filePath)
        {
            FileStream fstream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            WebRequest wRequest = WebRequest.Create(url);
            try
            {
                WebResponse wResponse = wRequest.GetResponse();
                int contentLength = (int)wResponse.ContentLength;

byte[] buffer = new byte[Properties.Settings.Default.byte_size];

///备注:Properties.Settings.Default.byte_size是从配置文件中读取的
                int read_count = 0;
                int total_read_count = 0;
                bool complete = false;

System.Console.WriteLine("开始下载文件....");

while (!complete)
                {
                    read_count = wResponse.GetResponseStream().Read(buffer, 0, buffer.Length);
                    if (read_count > 0)
                    {
                        fstream.Write(buffer, 0, read_count);
                        total_read_count += read_count;
                        if (total_read_count <= contentLength)
                            System.Console.Write(".");
                    }
                    else
                    {
                        complete = true;
                        System.Console.WriteLine("");
                        System.Console.WriteLine("下载完成!开始安装!");

}
                }
                fstream.Flush();
                return true;
            }
           catch(Exception ex)
            {
                throw ex;
             }
            finally
            {
                fstream.Close();
                wRequest = null;
            }
        }
       #endregion

}
}

【2】解压缩文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace XuanWu.Software.EasyInfo.Interface.Update
{
    public class UnZipClass
    {
        private byte[] byffer = new byte[Properties.Settings.Default.byte_size];

///备注:Properties.Settings.Default.byte_size是从配置文件中读取的

/// <summary>
        /// 有参构造函数
        /// </summary>
        /// <param name="buffserSize">缓冲大小</param>
        public UnZipClass(int buffserSize)
        { 
            byffer = new byte[buffserSize];
        }

/// <summary>
        /// 无参构造函数
        /// </summary>
        public UnZipClass()
        { }

/// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="unZipFilePath">解压缩文件路径</param>
        public void UnZipFile(string zipFilePath, string unZipFilePath)
        {
            using (ZipInputStream zipstream = new ZipInputStream(File.OpenRead(zipFilePath)))
            {
                ZipEntry zipEntry = null;
                while ((zipEntry = zipstream.GetNextEntry()) != null)
                {
                    string fileName = Path.GetFileName(zipEntry.Name);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        if (zipEntry.CompressedSize == 0)
                            break;

using (FileStream stream = File.Create(unZipFilePath + fileName))
                        {
                            while (true)
                            {
                                int size = zipstream.Read(byffer, 0, byffer.Length);
                                if (size > 0)
                                    stream.Write(byffer, 0, size);
                                else break;
                            }
                        }
                    }
                }
            }
        }

/// <summary>
        /// 解压缩目录
        /// </解压缩目录summary>
        /// <param name="zipDirectoryPath">压缩目录路径</param>
        /// <param name="unZipDirectoryPath">解压缩目录路径</param>
        public void UnZipDirectory(string zipDirectoryPath, string unZipDirectoryPath)
        { 
            using(ZipInputStream zipStream = new ZipInputStream(File.OpenRead(zipDirectoryPath)))
            {
                ZipEntry zipentry = null;
                while ((zipentry = zipStream.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(zipentry.Name);
                    string fileName = Path.GetFileName(zipentry.Name);

if (!string.IsNullOrEmpty(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

if (!string.IsNullOrEmpty(fileName))
                    {
                        if (zipentry.CompressedSize == 0)
                            break;
                        if (zipentry.IsDirectory)
                        {
                            directoryName = Path.GetDirectoryName(unZipDirectoryPath + zipentry.Name);
                            Directory.CreateDirectory(directoryName);
                        }

using (FileStream stream = File.Create(unZipDirectoryPath + zipentry.Name))
                        {
                            while (true)
                            {
                                int size = zipStream.Read(byffer, 0, byffer.Length);
                                if (size > 0)
                                    stream.Write(byffer, 0, size);
                                else break;
                            }
                        }

}
                }
            }
        }

}
}

【3】控制台应用程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Diagnostics;
using System.IO;
using XuanWu.Software.EasyInfo.Model;
using XuanWu.Software.EasyInfo.Service.elsp_da;

namespace XuanWu.Software.EasyInfo.Interface.Update
{
    class Program
    {
        static void Main(string[] args)
        {

Protocol.ProtocolRegister.RegisterProcotols();

string path = "http://" + Properties.Settings.Default.urlServerIP + ":" + Properties.Settings.Default.urlServerPort + "/soft/";

///备注:Properties.Settings.Default.urlServerIP和Properties.Settings.Default.urlServerPort 是从配置文件中读取的
            string Version = Properties.Settings.Default.Version;   ///版本号
            string buildno = Properties.Settings.Default.buildno;   ///版本状态
            string clienttypeno = Properties.Settings.Default.clienttypeno;  ///版本类型

///备注:上面3个变量的赋值都是从配置文件中取的。
            try
            {

///从本地文件中读取值,如果没有存在文件,报错跳出Try语句.Application.StartupPath + "//Version.bt");

buildno = File.ReadAllText(System.Windows.Forms.Application.StartupPath + "//buildno.bt");

clienttypeno = File.ReadAllText(System.Windows.Forms.Application.StartupPath + "//clienttypeno.bt");
            }
            catch { }
            updatesoftwareobj updatesfoj = getsoftwareobj(Convert.ToInt32(buildno), Convert.ToInt32(Version), Convert.ToInt32(clienttypeno));

///备注:updatesoftwareobj 实体对象
            if (updatesfoj != null)
            {
                path += updatesfoj.updateurl;
                int versionstatus = updatesfoj.versionstatus;
                string  serverVersion = updatesfoj.versionno.ToString();
                string serverbuildno = updatesfoj.buildno.ToString();
                string serverclienttypeno = updatesfoj.clienttypeno.ToString();
                try
                {
                    if (Convert.ToInt32(serverbuildno)> Convert.ToInt32(buildno))
                    {
                        System.Console.WriteLine("开始升级....");
                        System.Console.WriteLine("————————————————————————");
                        System.Console.WriteLine("开始下载......");
                        DownloadThread down = new DownloadThread();
                        down.DownLoadOneFile(path, System.Windows.Forms.Application.StartupPath + "//updata.zip");
                        System.Console.WriteLine("————————————————————————");
                        System.Console.WriteLine("开始更新......");
                        UnZipClass unzip = new UnZipClass();
                        unzip.UnZipFile(System.Windows.Forms.Application.StartupPath + "//updata.zip", System.Windows.Forms.Application.StartupPath + "//");
                        unzip.UnZipDirectory(System.Windows.Forms.Application.StartupPath + "//updata.zip", System.Windows.Forms.Application.StartupPath + "//");
                        File.Delete(System.Windows.Forms.Application.StartupPath + "//updata.zip");
                        System.Console.WriteLine("更新完成!");
                        System.Console.WriteLine("————————————————————————");
                        System.Console.WriteLine("启动服务程序!");
                        File.WriteAllText(System.Windows.Forms.Application.StartupPath + "//Version.bt", serverVersion);
                        File.WriteAllText(System.Windows.Forms.Application.StartupPath + "//buildno.bt", serverbuildno);
                        File.WriteAllText(System.Windows.Forms.Application.StartupPath + "//clienttypeno.bt", serverclienttypeno);
                        Process.Start(System.Windows.Forms.Application.StartupPath + "//某服务.exe");
                    }
                }
                catch (Exception ex)
                {
                    File.WriteAllText(System.Windows.Forms.Application.StartupPath + "//installLog.erroe", ex.ToString());
                    System.Console.WriteLine(ex.ToString());
                }
            }
        }

/// <summary>
        ///端版本号及版本号获取是否有相应的更新信息
        /// </summary>
        /// <param name="buildno"></param>
        /// <param name="versionno"></param>
        /// <param name="clienttypeno"></param>
        /// <returns></returns>
        private static updatesoftwareobj getsoftwareobj(int buildno, int versionno, int clienttypeno)
        {
            DateSourceSystemService datasystesv = new DateSourceSystemService(IPAddress.Parse(Properties.Settings.Default.ServerIP), Properties.Settings.Default.ServerPort);
            updatesoftwareobj updatestobj = datasystesv.getbymodelversion(buildno,versionno,clienttypeno);
            return updatestobj;
        }
    }
}

 

C#在线更新程序[下载程序、解压缩程序、控制台程序]的更多相关文章

  1. VC无窗口控制台程序

    VC无窗口控制台程序 #pragma comment(linker,"/subsystem:\"Windows\" /entry:\"mainCRTStartu ...

  2. Ninject之旅之二:开始使用Ninject(附程序下载)

    摘要 这篇文章介绍怎样将Ninject添加到实际的项目中,使用Ninject框架最基本的功能.首先用一个Hello World例子介绍怎么添加和使用Ninject.然后用一个更复杂的例子,介绍Ninj ...

  3. NHibernate系列文章二十八:NHibernate Mapping之Auto Mapping(附程序下载)

    摘要 上一篇文章介绍了Fluent NHibernate基础知识.但是,Fluent NHibernate提供了一种更方便的Mapping方法称为Auto Mapping.只需在代码中定义一些Conv ...

  4. C#控制台程序的参数解析类库 CommandLine简单使用说明

    前言 C#开发的控制台程序,默认接收string[] args参数.如果有多个参数需要输入时,可以按照顺序依次输入:但如果有些参数不是必选的,或者有些参数中间需要有空格比如时间“2016-05-18 ...

  5. Mac OS X上用CoreCLR运行一个真正的.NET控制台程序

    这个真正的控制台程序来自corefxlab,名叫CoreClrHelloWorld,是一个跨平台的.NET控制台演示程序,可以显示微软.Linux.苹果的logo. CoreClrHelloWorld ...

  6. VC6.0建立控制台程序实现PDA应用

    作者:iamlaosong 由于须要,又写起了文本界面的程序,以便PDA通过telnet连上运行. 假设是Linuxserver的话.这是非常easy的事,但是用户server是windows ser ...

  7. 控制台程序的参数解析类库 CommandLine

    C#控制台程序的参数解析类库 CommandLine简单使用说明 前言 C#开发的控制台程序,默认接收string[] args参数.如果有多个参数需要输入时,可以按照顺序依次输入:但如果有些参数不是 ...

  8. Ninject之旅之十三:Ninject在ASP.NET MVC程序上的应用(附程序下载)

    摘要: 在Windows客户端程序(WPF和Windows Forms)中使用Ninject和在控制台应用程序中使用Ninject没什么不同.在这些应用程序里我们不需要某些配置用来安装Ninject, ...

  9. C#控制台程序使用Log4net日志组件

    1.Log4net一般都不陌生,但是在配置上不同类型的项目又不相同的地方比如C#控制台程序和C# MVCWeb项目,拿控制台项目为例   项目源码在文章底部 2.首先创建一个控制台程序,引入Log4n ...

  10. 使用VSCode如何调试C#控制台程序_1

    A-环境安装 https://www.microsoft.com/net/download 下载 .NET Core SDK Installer: https://www.microsoft.com/ ...

随机推荐

  1. maven概念

     1. 下载并解压Maven:Maven下载页2. 将环境变量M2_HOME设置为解压后的目录: 3. 将M2环境变量设置为M2_HOME/bin(在Windows上是%M2_HOME%/bin,在U ...

  2. SQLserver批量删除空表

    今天需要清理一个很大的数据库,里面表有一堆,而且有很多是空表.想着把数据库弄小点,于是想到一次性删掉所有空表. 废话不多说,上代码. 首先,查处所有的空表. select distinct a.nam ...

  3. sqlplus入门基础语句

    关于Oracle 首先Oracle一个数据库由若干个表空间组成,每个表空间由若干个数据文件(或设备)组成,每个数据文件由若干个盘区组成,每个盘区由若干个block组成.这是Oracle的物理结构. 逻 ...

  4. 在 Windows XP 下查看所有卷标信息

    http://support.hp.com/cn-zh/document/c01270024 点击“开始”,在“开始搜索”中输入:diskpart,然后按键盘“回车”键. 在“命令行窗口”中,等待“D ...

  5. Java编程思想学习笔记_4(异常机制,容器)

    一.finally语句注意的细节: 当涉及到break和continue语句的时候,finally字句也会得到执行. public class Test7 { public static void m ...

  6. Ubuntu 查看文件以及磁盘空间大小管理

    (1)查看文件大小  查看当前文件夹下所有文件大小(包括子文件夹)    du -sh   # du -h15M     ./package16K     ./.fontconfig4.0K    . ...

  7. tabhost切换标签:Log中出现You must supply a layout_width attribute的解决方法

    谷歌.百度该问题,发现,除非是真的忘记添加layout_height或者layout_width属性值,对于布局文件没有语法问题但又难以发现问题所在的情况,从自己的经历和一个帖子的说明看到,该错误多半 ...

  8. LocalStorage在Chrome里的实现

    前段时间我们在实现CanTK-Runtime时,也曾在V8基础上模拟过浏览器的LocaleStorage功能,其实现非常简单:每个domain的数据使用的单独文件存储,因为同一时间只有一个游戏运行,所 ...

  9. 【BZOJ 3295】动态逆序对 - 分块+树状数组

    题目描述 给定一个1~n的序列,然后m次删除元素,每次删除之前询问逆序对的个数. 分析:分块+树状数组 (PS:本题的CDQ分治解法见下一篇) 首先将序列分成T块,每一块开一个树状数组,并且先把最初的 ...

  10. 字符串(string)转json

    第一种方式: 使用js函数eval(); testJson=eval(testJson);是错误的转换方式. 正确的转换方式需要加(): testJson = eval("(" + ...