winform 升级程序 包含自动监测版本,winform自动下载文件,winform自动升级!!!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

///作者:https://blog.csdn.net/u010919083/
namespace AutoUpdate
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        string Rootpath = Environment.CurrentDirectory;

        /// <summary>
        /// 要下载网络升级包的地址
        /// </summary>
        string ServerPathUrl = Common.FilePathConfig.DownZIPUrl;

        /// <summary>
        /// 本地存储目录
        /// </summary>
        string ZipFilePath = Common.FilePathConfig.DownZIPPath;
        /// <summary>
        /// 本地解压目录
        /// </summary>
        string UnFilePath = Common.FilePathConfig.UnDownZIPPath;

        /// <summary>
        /// 开始升级程序客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Start_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
            Thread th = new Thread(StartUpdate);
            th.IsBackground = true;
            th.Start();
        }
        /// <summary>
        /// 开始下载文件 升级
        /// </summary>
        private void StartUpdate()
        {
            bool result = Common.HttpHelper.HttpDownload(ServerPathUrl, ZipFilePath, this.progressBar1, this.label2_tishi);
            timer1.Enabled = false;
            if (result)
            {
                RefThisForm("下载成功!");
                Thread.Sleep(100);
                RefThisForm("正在解压,请稍后");
                if (!Directory.Exists(UnFilePath))
                    Directory.CreateDirectory(UnFilePath);
                //UnFilePath = new FileInfo(ZipFilePath).DirectoryName;


                string reusult = Common.ZIPHelper.UnZipFile(ZipFilePath,UnFilePath);
                if (reusult != "")
                {
                    RefThisForm("解压成功!");
                    CheckUnZIPFile(reusult);
                }
                else
                {
                    RefThisForm("解压失败!压缩包路径:" + ZipFilePath);
                }
            }
            else
            {
                MessageBox.Show("下载失败!");
            }


        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            FrmMain.CheckForIllegalCrossThreadCalls = false;

            //删除陈旧的历史下载记录ZIP信息
            try
            {
                File.Delete(ZipFilePath);
            }
            catch (Exception ex)
            {

            }
            //检查下载器文件的dll

            button1_Start_Click(null, null);

        }
        private void CheckFile()
        {
            string UnZipdllPath = Rootpath + "/ICSharpCode.SharpZipLib.dll";         
            if (!File.Exists(UnZipdllPath))
            {
                MessageBox.Show("下载器文件丢失:ICSharpCode.SharpZipLib.dll");
            }
        }

        /// <summary>
        /// 检查文件 解压
        /// </summary>
        /// <param name="UnZipFilePath"></param>
        private void CheckUnZIPFile(string UnZipFileDirPath)
        { 
            string mainexe = UnZipFileDirPath + "/WinForm.exe";
            Directory.SetCurrentDirectory(Directory.GetParent(UnZipFileDirPath).FullName);
            string OldFolder = Directory.GetCurrentDirectory();
            if (!File.Exists(mainexe))
            {
                MessageBox.Show("未能找到主程序:" + mainexe);
                return;
            }
            else {
                //覆盖源目录文件 
                // string result=Common.FileHelper.CopyFolder(OldFolder,UnZipFileDirPath);
                //MessageBox.Show("请确认开始替换原始文件!");
                RefThisForm("安装中..."); //RefThisForm("替换原始主程序中。。。。");
               
                bool result1=Common.FileHelper.CopyOldLabFilesToNewLab(UnZipFileDirPath,OldFolder,0);
                if (result1)
                {
                    RefThisForm("安装中..."); //RefThisForm("替换原始程序完毕。。。。");
                    //清空解压的文件
                    FileInfo fileinfo = new FileInfo(UnZipFileDirPath);
                    try
                    {
                        if (Directory.Exists(fileinfo.FullName))
                        {
                            // MessageBox.Show("要删除的文件目录:" + fileinfo.FullName);
                            Common.FileHelper.DelectDir(fileinfo.FullName);
                            Common.FileHelper.DelectDir(Common.FilePathConfig.UnDownZIPPath);
                            GC.Collect();
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("清理下载文件垃圾失败!"+ex.ToString());
                    }
                }
                else
                {
                    MessageBox.Show("升级失败!");
                }
            }
            //2. 启动新下载的程序  
        
            StartNewSystem();

            GC.Collect();

        }
        /// <summary>
        /// 启动最新下载的程序
        /// </summary>
        private void StartNewSystem()
        {
            string path = Environment.CurrentDirectory;
            Directory.SetCurrentDirectory(Directory.GetParent(path).FullName);
            path = Directory.GetCurrentDirectory();
            string mainexe = path + "/WinForm.exe";
            if (File.Exists(mainexe))
            {
                Process.Start(mainexe);
            }
            ///清理下载的文件的缓存垃圾
            GC.Collect();
            
        }
        private void RefThisForm(string text)
        {
            this.Text = text;
        }
        /// <summary>
        /// 时间  戳 事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            //Console.WriteLine("时间timer\r\n"+DateTime.Now.ToString()+"\r\n");

            label2_tishi.Text = progressBar1.Value/1048576+"M/"+ progressBar1.Maximum/ 1048576 + "M";
            if(progressBar1.Value== progressBar1.Maximum)
                label2_tishi.Text= progressBar1.Maximum / 1048576 + "M/" + progressBar1.Maximum / 1048576 + "M";
        }


    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AutoUpdate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string url = "http://192.168.149.1:8080/publish/version.txt";
            string s1=Common.HttpHelper.SendGetRequest(url);
            MessageBox.Show(s1);
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace AutoUpdate.Common
{
    public class FileHelper
    {
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="DirectoryPath">要创建的文件夹路径</param>
        /// <returns></returns>
        public static string CreateDirectory(string DirectoryPath)
        {
            try
            {
                if (!Directory.Exists(DirectoryPath))
                    Directory.CreateDirectory(DirectoryPath);
                return DirectoryPath;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 指定目录覆盖指定目录
        /// </summary>
        /// <param name="strFromPath">要复制的目录</param>
        /// <param name="strToPath">要覆盖的目录</param>
        public static string CopyFolder(string strFromPath, string strToPath)
        {
            try
            {
                //如果源文件夹不存在,则创建
                if (!Directory.Exists(strFromPath))
                {
                    Directory.CreateDirectory(strFromPath);
                }
                //取得要拷贝的文件夹名
                string strFolderName = strFromPath.Substring(strFromPath.LastIndexOf("\\") +
                   1, strFromPath.Length - strFromPath.LastIndexOf("\\") - 1);
                //如果目标文件夹中没有源文件夹则在目标文件夹中创建源文件夹
                if (!Directory.Exists(strToPath + "\\" + strFolderName))
                {
                    Directory.CreateDirectory(strToPath + "\\" + strFolderName);
                }
                //创建数组保存源文件夹下的文件名
                string[] strFiles = Directory.GetFiles(strFromPath);
                //循环拷贝文件
                for (int i = 0; i < strFiles.Length; i++)
                {
                    //取得拷贝的文件名,只取文件名,地址截掉。
                    string strFileName = strFiles[i].Substring(strFiles[i].LastIndexOf("\\") + 1, strFiles[i].Length - strFiles[i].LastIndexOf("\\") - 1);
                    //开始拷贝文件,true表示覆盖同名文件
                    File.Copy(strFiles[i], strToPath + "\\" + strFolderName + "\\" + strFileName, true);
                }
                //创建DirectoryInfo实例
                DirectoryInfo dirInfo = new DirectoryInfo(strFromPath);
                //取得源文件夹下的所有子文件夹名称
                DirectoryInfo[] ZiPath = dirInfo.GetDirectories();
                for (int j = 0; j < ZiPath.Length; j++)
                {
                    //获取所有子文件夹名
                    string strZiPath = strFromPath + "\\" + ZiPath[j].ToString();
                    //把得到的子文件夹当成新的源文件夹,从头开始新一轮的拷贝
                    CopyFolder(strZiPath, strToPath + "\\" + strFolderName);

                   
                }

                return strToPath;
            }
            catch (Exception ex)
            {
                return "";
            }
        }


        /// <summary>
        /// 拷贝oldlab的文件到newlab下面
        /// </summary>
        /// <param name="sourcePath">lab文件所在目录(@"~\labs\oldlab")</param>
        /// <param name="savePath">保存的目标目录(@"~\labs\newlab")</param>
        /// <param name="TypeDown">0 是升级主程序,1 是升级 下载器</param>
        /// <returns>返回:true-拷贝成功;false:拷贝失败</returns>
        public static bool CopyOldLabFilesToNewLab(string sourcePath, string savePath,int TypeDown)
        {
            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }
            RemoveDirectory(savePath);

            #region //拷贝labs文件夹到savePath下
            try
            {
                string[] labDirs = Directory.GetDirectories(sourcePath);//目录
                string[] labFiles = Directory.GetFiles(sourcePath);//文件
                if (labFiles.Length > 0)
                {
                    for (int i = 0; i < labFiles.Length; i++)
                    {
                        if (ReCopy(Path.GetFileName(labFiles[i]).ToString(),TypeDown))//排除.lab文件
                        {
                            File.Copy(sourcePath + "\\" + Path.GetFileName(labFiles[i]), savePath + "\\" + Path.GetFileName(labFiles[i]), true);
                        }
                    }
                }
                if (labDirs.Length > 0)
                {
                    for (int j = 0; j < labDirs.Length; j++)
                    {
                        Directory.GetDirectories(sourcePath + "\\" + Path.GetFileName(labDirs[j]));

                        //递归调用
                        CopyOldLabFilesToNewLab(sourcePath + "\\" + Path.GetFileName(labDirs[j]), savePath + "\\" + Path.GetFileName(labDirs[j]), TypeDown);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("升级遇到异常:" + ex.ToString());
                return false;
            }
            #endregion
            return true;
        }

        /// <summary>
        /// 指定是否CoPy 这里先直接列出来
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="TypeDown"></param>
        /// <returns></returns>
        public static bool ReCopy(string filepath,int TypeDown)
        {
            //下载器文件跳过
            if (filepath.Contains("AutoUpdate.exe")|| filepath.Contains("ICSharpCode.SharpZipLib.dll"))
            {
                return false;
            }
            //本地密码文件和服务器IP配置文件
            if (filepath.Contains(".ini")|| filepath.Contains("System.xml"))
                return false;
            //本地存储数据文件 
            if (filepath.Contains(".db"))
                return false;
            return true;
        }
        /// <summary>
        /// 要移出只读属性的文件夹目录
        /// </summary>
        /// <param name="RootSystemDir"></param>
        /// <returns></returns>
        public static bool RemoveDirectory(string RootSystemDir)
        {
            try {

                //去除文件夹的只读属性: 
                System.IO.DirectoryInfo DirInfo = new DirectoryInfo(RootSystemDir);
                DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

                //去除文件的只读属性: System.IO.File.SetAttributes("filepath", System.IO.FileAttributes.Normal);

                string [] fileinfo = Directory.GetFiles(DirInfo.FullName.ToString());
                for (int i = 0; i < fileinfo.Length; i++)
                {
                    System.IO.File.SetAttributes(fileinfo[i], System.IO.FileAttributes.Normal);
                }


                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// 删除指定目录的文件和文件夹
        /// </summary>
        /// <param name="srcPath"></param>
        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
                Directory.Delete(srcPath);
            }
            catch (Exception e)
            {
                
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AutoUpdate.Common
{
    /// <summary>
    /// 设置 文件ZIP 操作目录 类
    /// </summary>
    public  class FilePathConfig
    {

        public static string DownServer = "http://59.110.110.110:10021/";

        /// <summary>
        /// 要下载更新程序的网络路径
        /// </summary>
        public static string DownZIPUrl = "http://59.110.110.110:110/NewVersion.zip";

        ///// <summary>
        ///// 下载文件后的ZIP 文件保存的本地目录
        ///// </summary>
        //public static string DownZIPPath = System.Environment.CurrentDirectory+"/"+DateTime.Now.ToString("yyyy_NewVersion") +"/New.zip";

        ///// <summary>
        ///// 解压ZIP后的保存目录 注意这里是文件夹
        ///// </summary>
        //public static string UnDownZIPPath = System.Environment.CurrentDirectory+"//"+ DateTime.Now.ToString("yyyy_NewVersion_File");    

        /// <summary>
        /// 下载文件后的ZIP 文件保存的本地目录
        /// </summary>
        public static string DownZIPPath = System.Environment.CurrentDirectory + "/" + DateTime.Now.ToString("yyyy")+ "_NewVersion" + "/New.zip";

        /// <summary>
        /// 解压ZIP后的保存目录 注意这里是文件夹
        /// </summary>
        public static string UnDownZIPPath = System.Environment.CurrentDirectory + "//" + DateTime.Now.ToString("yyyy")+ "_NewVersion_File";
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace AutoUpdate.Common
{
    /// <summary>
    /// 专门的下载文件类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// http下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="path"></param>
        /// </summary>
        /// <param name="url">下载文件地址</param>
        /// <param name="path">文件存放地址,包含文件名</param>
        /// <param name="progressBar1"></param>
        /// <param name="label_Info">提示信息 ,时时提示下载多少K的 </param>
        /// <returns></returns>
        public static bool HttpDownload(string url, string path, ProgressBar progressBar1, Label label_Info)
        {
            string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";
            if (!System.IO.Directory.Exists(tempPath))
                System.IO.Directory.CreateDirectory(tempPath);  //创建临时文件目录
            string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //临时文件
            try
            {
                FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                //Stream stream = new FileStream(tempFile, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);


                if (response.ContentLength != 0)
                {
                    if (request.ContentLength > int.MaxValue)
                    {
                        MessageBox.Show("要下载的文件太大,超出范围!");
                        return false;
                    }

                    progressBar1.Maximum = Convert.ToInt32(response.ContentLength.ToString());
                }

                while (size > 0)
                {
                    //stream.Write(bArr, 0, size);
                    fs.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);

                    progressBar1.Invoke(new Action(() => {
                        progressBar1.Value += size;
                    }));
                }
                fs.Close();
                responseStream.Close();
                System.IO.File.Move(tempFile, path);

                if (System.IO.File.Exists(tempFile))
                {
                    System.IO.File.Delete(tempFile);    //存在则删除
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        delegate  void SetTextCallBack(string text,Label txt_a);
        private static void SetText(string text, Label txt_a)
        {
            if (txt_a.InvokeRequired)
            {
                SetTextCallBack stcb = new SetTextCallBack(SetText);
                txt_a.Invoke(stcb, new object[] { text, txt_a });
            }
            else
            {
                txt_a.Text = text;
            }
        }



        public static string SendGetRequest(string url)
        {
            try
            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "get";

                //if (CookiesContainer == null)
                //{
                //    CookiesContainer = new CookieContainer();
                //}

                //request.CookieContainer = CookiesContainer;  //启用cookie

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream response_stream = response.GetResponseStream();

                int count = (int)response.ContentLength;
                int offset = 0;
                byte[] buf = new byte[count];
                while (count > 0)  //读取返回数据
                {
                    int n = response_stream.Read(buf, offset, count);
                    if (n == 0) break;
                    count -= n;
                    offset += n;
                }
                return Encoding.UTF8.GetString(buf);
            }
            catch
            {
                return null;
            }
        }




    }
}
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

///作者:https://blog.csdn.net/u010919083/
namespace AutoUpdate.Common
{
    /// <summary>   
    /// 适用与ZIP压缩   
    /// </summary>   
    public class ZIPHelper
    {
        #region 压缩  

        /// <summary>   
        /// 递归压缩文件夹的内部方法   
        /// </summary>   
        /// <param name="folderToZip">要压缩的文件夹路径</param>   
        /// <param name="zipStream">压缩输出流</param>   
        /// <param name="parentFolderName">此文件夹的上级文件夹</param>   
        /// <returns></returns>   
        private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
        {
            bool result = true;
            string[] folders, files;
            ZipEntry ent = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();

            try
            {
                ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
                zipStream.PutNextEntry(ent);
                zipStream.Flush();

                files = Directory.GetFiles(folderToZip);
                foreach (string file in files)
                {
                    fs = File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
                    ent.DateTime = DateTime.Now;
                    ent.Size = fs.Length;

                    fs.Close();

                    crc.Reset();
                    crc.Update(buffer);

                    ent.Crc = crc.Value;
                    zipStream.PutNextEntry(ent);
                    zipStream.Write(buffer, 0, buffer.Length);
                }

            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }

            folders = Directory.GetDirectories(folderToZip);
            foreach (string folder in folders)
                if (!ZipDirectory(folder, zipStream, folderToZip))
                    return false;

            return result;
        }

        /// <summary>   
        /// 压缩文件夹    
        /// </summary>   
        /// <param name="folderToZip">要压缩的文件夹路径</param>   
        /// <param name="zipedFile">压缩文件完整路径</param>   
        /// <param name="password">密码</param>   
        /// <returns>是否压缩成功</returns>   
        public static bool ZipDirectory(string folderToZip, string zipedFile, string password)
        {
            bool result = false;
            if (!Directory.Exists(folderToZip))
                return result;

            ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
            zipStream.SetLevel(6);
            if (!string.IsNullOrEmpty(password)) zipStream.Password = password;

            result = ZipDirectory(folderToZip, zipStream, "");

            zipStream.Finish();
            zipStream.Close();

            return result;
        }

        /// <summary>   
        /// 压缩文件夹   
        /// </summary>   
        /// <param name="folderToZip">要压缩的文件夹路径</param>   
        /// <param name="zipedFile">压缩文件完整路径</param>   
        /// <returns>是否压缩成功</returns>   
        public static bool ZipDirectory(string folderToZip, string zipedFile)
        {
            bool result = ZipDirectory(folderToZip, zipedFile, null);
            return result;
        }

        /// <summary>   
        /// 压缩文件   
        /// </summary>   
        /// <param name="fileToZip">要压缩的文件全名</param>   
        /// <param name="zipedFile">压缩后的文件名</param>   
        /// <param name="password">密码</param>   
        /// <returns>压缩结果</returns>   
        public static bool ZipFile(string fileToZip, string zipedFile, string password)
        {
            bool result = true;
            ZipOutputStream zipStream = null;
            FileStream fs = null;
            ZipEntry ent = null;

            if (!File.Exists(fileToZip))
                return false;

            try
            {
                fs = File.OpenRead(fileToZip);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                fs = File.Create(zipedFile);
                zipStream = new ZipOutputStream(fs);
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                ent = new ZipEntry(Path.GetFileName(fileToZip));
                zipStream.PutNextEntry(ent);
                zipStream.SetLevel(6);

                zipStream.Write(buffer, 0, buffer.Length);

            }
            catch
            {
                result = false;
            }
            finally
            {
                if (zipStream != null)
                {
                    zipStream.Finish();
                    zipStream.Close();
                }
                if (ent != null)
                {
                    ent = null;
                }
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
            GC.Collect();
            GC.Collect(1);

            return result;
        }

        /// <summary>   
        /// 压缩文件   
        /// </summary>   
        /// <param name="fileToZip">要压缩的文件全名</param>   
        /// <param name="zipedFile">压缩后的文件名</param>   
        /// <returns>压缩结果</returns>   
        public static bool ZipFile(string fileToZip, string zipedFile)
        {
            bool result = ZipFile(fileToZip, zipedFile, null);
            return result;
        }

        /// <summary>   
        /// 压缩文件或文件夹   
        /// </summary>   
        /// <param name="fileToZip">要压缩的路径</param>   
        /// <param name="zipedFile">压缩后的文件名</param>   
        /// <param name="password">密码</param>   
        /// <returns>压缩结果</returns>   
        public static bool Zip(string fileToZip, string zipedFile, string password)
        {
            bool result = false;
            if (Directory.Exists(fileToZip))
                result = ZipDirectory(fileToZip, zipedFile, password);
            else if (File.Exists(fileToZip))
                result = ZipFile(fileToZip, zipedFile, password);

            return result;
        }

        /// <summary>   
        /// 压缩文件或文件夹   
        /// </summary>   
        /// <param name="fileToZip">要压缩的路径</param>   
        /// <param name="zipedFile">压缩后的文件名</param>   
        /// <returns>压缩结果</returns>   
        public static bool Zip(string fileToZip, string zipedFile)
        {
            bool result = Zip(fileToZip, zipedFile, null);
            return result;

        }

        #endregion

        #region 解压  

        /// <summary>   
        /// 解压功能(解压压缩文件到指定目录)   
        /// </summary>   
        /// <param name="fileToUnZip">待解压的文件</param>   
        /// <param name="zipedFolder">指定解压目标目录</param>   
        /// <param name="password">密码</param>   
        /// <returns>解压结果</returns>   
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            bool result = true;
            FileStream fs = null;
            ZipInputStream zipStream = null;
            ZipEntry ent = null;
            string fileName;

            if (!File.Exists(fileToUnZip))
                return false;

            if (!Directory.Exists(zipedFolder))
                Directory.CreateDirectory(zipedFolder);

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi   

                        if (fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }

                        fs = File.Create(fileName);
                        int size = 2048;
                        byte[] data = new byte[size];
                        while (true)
                        {
                            size = zipStream.Read(data, 0, data.Length);
                            if (size > 0)
                                fs.Write(data, 0, data.Length);
                            else
                                break;
                        }
                    }
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return result;
        }

        /// <summary>   
        /// 解压功能(解压压缩文件到指定目录)   
        /// </summary>   
        /// <param name="fileToUnZip">待解压的文件</param>   
        /// <param name="zipedFolder">指定解压目标目录</param>   
        /// <returns>解压结果</returns>   
        public static bool UnZip(string fileToUnZip, string zipedFolder)
        {
            bool result = UnZip(fileToUnZip, zipedFolder, null);
            return result;
        }

        #endregion

        #region  使用GZIP解压
        public static bool  UnZipFile(string zipFilePath)
        {
            if (!File.Exists(zipFilePath))
            {
                //Console.WriteLine("Cannot find file '{0}'", zipFilePath);
                return false;
            }
            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {

                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {

                        //Console.WriteLine(theEntry.Name);

                        string directoryName =Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);

                        // create directory
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(directoryName);
                        }

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(theEntry.Name))
                            {

                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 解压文件 
        /// </summary>
        /// <param name="TargetFile">ZIP路径</param>
        /// <param name="fileDir">解压到的路径</param>
        /// <returns></returns>
        public static string UnZipFile(string TargetFile, string fileDir)
        {
            string rootFile = " ";
            try
            {
                //读取压缩文件(zip文件),准备解压缩
                ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
                ZipEntry theEntry;
                string path = fileDir;
                //解压出来的文件保存的路径

                string rootDir = " ";
                //根目录下的第一个子文件夹的名称
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    rootDir = Path.GetDirectoryName(theEntry.Name);
                    //得到根目录下的第一级子文件夹的名称
                    if (rootDir.IndexOf("\\") >= 0)
                    {
                        rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                    }
                    string dir = Path.GetDirectoryName(theEntry.Name);
                    //根目录下的第一级子文件夹的下的文件夹的名称
                    string fileName = Path.GetFileName(theEntry.Name);
                    //根目录下的文件名称
                    if (dir != " ")
                    //创建根目录下的子文件夹,不限制级别
                    {
                        if (!Directory.Exists(fileDir + "\\" + dir))
                        {
                            path = fileDir + "\\" + dir;
                            //在指定的路径创建文件夹
                            Directory.CreateDirectory(path);
                            //MessageBox.Show(path);
                        }
                    }
                    else if (dir == " " && fileName != "")
                    //根目录下的文件
                    {
                        path = fileDir;
                        rootFile = fileName;
                    }
                    else if (dir != " " && fileName != "")
                    //根目录下的第一级子文件夹下的文件
                    {
                        if (dir.IndexOf("\\") > 0)
                        //指定文件保存的路径
                        {
                            path = fileDir + "\\" + dir;
                        }
                    }

                    if (dir == rootDir)
                    //判断是不是需要保存在根目录下的文件
                    {
                        path = fileDir + "\\" + rootDir;
                    }

                    //以下为解压缩zip文件的基本步骤
                    //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
                    if (fileName != String.Empty)
                    {
                        FileStream streamWriter = File.Create(path + "\\" + fileName);

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }

                        streamWriter.Close();
                    }
                }
                s.Close();

                return fileDir;
            }
            catch (Exception ex)
            {
                MessageBox.Show("解压失败,升级包路径为:"+ fileDir+"\r\n"+"异常为:"+ex.ToString());
                return "";
            }
        }

        #endregion
    }

}

包含自动监测版本,自动下载文件,自动升级!!!

发布了123 篇原创文章 · 获赞 47 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/u010919083/article/details/99563924