C#在线更新程序[下载程序、解压缩程序、控制台程序]

【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;
        }
    }
}

时间: 2024-10-04 06:18:24

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

重定向子进程控制台程序的输入输出

重定向子进程控制台程序的输入输出 重定向所做的工作都在父进程,但需要子进程遵守下面的规则: 子进程程序在输出代码后,等待输入之前需要调用fflush(stdout)函数,这样把输出的内容放入缓冲区,父进程才能及时的读到输出数据. 不遵守以上规则就没办法实现有效的交互了,cmd.exe是遵守这个规则的典范,大部分控制台程序都不遵守这个规则.今天我试图给Google的V8 Javascript 的Shell搞一个GUI,方便我输入Javascript程序,就遇到了v8_shell不遵守这个的问题.好

网上下载的dubbo-admin控制台程序启动报错Bean property &#39;URIType&#39; is not writable

因为linux中使用的是jdk1.8,所以网上直接下载的dubbo-admin.war基本是2.5.4及以下的,如果放入tomcat中启动会报以下错误信息 Caused by: org.springframework.beans.NotWritablePropertyException: Invalid prope rty 'URIType' of bean class [com.alibaba.citrus.service.uribroker.uri.GenericURI Broker]: B

VS win32命令控制台程序与单片机串口数据传输

最近有个小的训练 大致是需要用摄像头检测圆,然后把圆的xy坐标发送给单片机. 但是网上大部分都是基于MFC串口控件的例程.大海捞针找到了个win32命令控制台的串口例程 ,自己改了一下贡献出来. 直接调用API实现串口通信 两个例程 如果编译运行有问题 直接复制源文件到新win32命令工程中运行 平台-VS2013-win32 例程1:摄像头识别小圆,然后通过串口输出小圆的xy坐标.单片机可以直接接受,具体串口配置自己配置.摄像头需要 opencv的库,我的库是opencv2.4.12. 例程2

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

前言 C#开发的控制台程序,默认接收string[] args参数.如果有多个参数需要输入时,可以按照顺序依次输入:但如果有些参数不是必选的,或者有些参数中间需要有空格比如时间“2016-05-18 24:35:00”,处理起来就比较麻烦了.一些常用的命令行工具都会提供指定参数的方式,比如:curl C:\Users\Administrator>curl --helpUsage: curl [options...] <url>Options: (H) means HTTP/HTTPS o

MiS603开发板 1.5 程序下载

作者:MiS603开发团队 日期:20150911 公司:南京米联电子科技有限公司 论坛:www.osrc.cn 网址:www.milinker.com 网店:http://osrc.taobao.com EAT博客:http://blog.chinaaet.com/whilebreak 博客园:http://www.cnblogs.com/milinker/ 1.5 程序下载 FPGA的程序下载分为2种形式:一种是通过JTAG接口将bit文件烧写到FPGA里面,这种烧写方式适用于程序调试,掉电

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

这个真正的控制台程序来自corefxlab,名叫CoreClrHelloWorld,是一个跨平台的.NET控制台演示程序,可以显示微软.Linux.苹果的logo. CoreClrHelloWorld代码如下(代码中省略了拼接logo的字符串,完整代码见这里): using System; internal class Program { private static void Main(string[] args) { if (args.Length == 1 && args[0] ==

VC6.0建立控制台程序

作者:iamlaosong 因为需要,又写起了文本界面的程序,以便PDA通过telnet连上执行.如果是Linux服务器的话,这是很简单的事,可是用户服务器是windows server 2003,所以就需要安装telnet服务,开发一个控制台程序.telnet服务器软件使用开源软件KpyM Telnet/SSH Server,控制台程序就用VC6.0来做了.网上搜了一下,通过下面链接操作即可: 怎么用VC6.0建立控制台程序 建议不要建立一个空程序,而是建立一个"Hello,World!&qu

Createprocess控制台程序输出重定向

在Windows编程中,并非每一个应用程序都需要一个图形用户界面(GUI),很多情况下,我们可以编写一个控制台应用程序,这样程序更小,加载更快,传输时间也短,同时也丝毫不牺牲程序应有的功能.这种程序特别适合那些在后台运行的程序,比如压缩.杀毒.上传下载等等.如果我们的确需要在GUI执行这些程序,以完成某些比如类似于磁盘格式化的功能,我们可以在GUI程序中创建一个新的进程,调用这些已有的控制台应用程序,帮助完成这些功能.然而令人失望的是,我们每次加载这些控制台应用程序时,图形程序总会在加载的过程中

【ASP.NET Core分布式项目实战】(五)Docker制作dotnet core控制台程序镜像

Docker制作dotnet core控制台程序镜像 基于dotnet SDK 新建控制台程序 mkdir /home/console cd /home/console dotnet new console dotnet restore 创建 Dockerfile 文件,参考https://github.com/dotnet/dotnet-docker/blob/master/samples/aspnetapp/Dockerfile vim /home/console/Dockerfile #

将程序下载到单片机

起首,我们要把硬件衔接好,把板子插到我们的电脑上,翻开装备治理器检查所运用的是哪个 COM 口,如图 2-21 所示,找到"USB-SERIAL CH340(COM5)"这一项,这里最初的数字就是开辟板今朝所运用的 COM 端标语. 图 2-21  检查COM口 然后 STC 系列单片的下载软件--STC-ISP,如图 2-22 所示. 图2-22  程序下载设置 下载软件列出了 5 个步调:第一步,选择单片机型号,我们如今用的单片机型号是STC89C52RC,这个必定不克不及选错了: