C# 文件压缩与解压

//文件的对话框
OpenFileDialog ofd = new OpenFileDialog();
//文件过滤器
ofd.Filter = "文本文档(*.txt)|*.txt|*.*|*.*";
//是否点击确定按钮
if (ofd.ShowDialog() == DialogResult.OK)
            {
                string fileName = ofd.FileName;//获取选择文件的文件名(全路径)
                textBox1.Text = fileName;
            }



//压缩

//判断是否选择了要解压的文件
if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                MessageBox.Show("必须选择需要压缩的文件");
                return;
            }
//判断文件是否存在
if (!File.Exists(textBox1.Text.Trim()))
    {
        MessageBox.Show("您选择的压缩文件不存在");
        return;
    }
            //获取 要压缩的文件的所在目录,此目录待会再生成压缩包时使用
            string fileBasePath = Path.GetDirectoryName(textBox1.Text.Trim());
            //获取 要压缩的文件的   去除后缀名之后的文件名
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(textBox1.Text.Trim());
            //zip压缩文件的文件名
            string zipFileName = fileNameWithoutExtension + ".zip";
            //zip文件的保存地址,即全路径
            string zipFilrePath = Path.Combine(fileBasePath, zipFileName);
            //创建一个压缩包(相当于创建一个项目)
            using (ZipFile zipfile = ZipFile.Create(zipFilrePath))
            {
                //开始更新压缩包   (相当于打开箱子)
                zipfile.BeginUpdate();
                //向压缩包中添加一个文件
                zipfile.Add(textBox1.Text.Trim(), Path.GetFileName(textBox1.Text.Trim()));
                //提交更新
                zipfile.CommitUpdate();
            }
            MessageBox.Show("压缩完成");



//选择压缩的压缩包

//实例化一个 选择文件的对话框
            OpenFileDialog ofd = new OpenFileDialog();
            //文件过滤器
            ofd.Filter = "压缩文件(*.zip)|*.zip";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string fileName = ofd.FileName;//获取选择文件的文件名(全路径)
                textBox2.Text = fileName;
            }


//选择解压目录
 FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string selectedPath = fbd.SelectedPath;//获取选择文件夹路径
                textBox3.Text = selectedPath;
            }


//开始解压
string zipFileName = textBox2.Text;
            string descFilePath = textBox3.Text;

            bool ret = this.Decompress(zipFileName, descFilePath);
            if (ret)
            {
                MessageBox.Show("解压成功");
            }
            else
            {
                MessageBox.Show("解压失败");
            }
/// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="sourceFile">压缩包完整路径地址</param>
        /// <param name="targetPath">解压路径是哪里</param>
        /// <returns></returns>
        public bool Decompress(string sourceFile, string targetPath)
        {
            //判断源文件是否存在
            if (!File.Exists(sourceFile))
            {
                throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
            }
            //判断目标文件夹是否存在
            if (!Directory.Exists(targetPath))
            {
                Directory.CreateDirectory(targetPath);
            }
            //创建一个ZipInput流, 并读取需要解压的压缩文件
            using (var zipInputStream = new ZipInputStream(File.OpenRead(sourceFile)))
            {
                //定义一个压缩条目项
                ZipEntry theEntry;
                while ((theEntry = zipInputStream.GetNextEntry()) != null)
                {
                    //获取 一个压缩条目项的 文件解压之后的目录:解压目录+条目目录
                    string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
                    //判断解压目录是否存在,如过不存在 则新建
                    if (!Directory.Exists(directorName))
                    {
                        Directory.CreateDirectory(directorName);
                    }
                    //判断条目是否是文件夹,如果是文件夹 则直接进行下一个循环
                    if (theEntry.IsDirectory)
                    { 
                        continue;
                    }
                    //能执行到这里,说明此条目是 是文件
                    //获取 一个压缩条目项的 文件解压之后的完整路径:目录+文件名
                    string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        //新建一个文件流,用来将一个条目项文件写到新的文件中
                        using (FileStream streamWriter = File.Create(fileName))
                        {
                            int size = 4*1024;//设置缓冲区大小,也就是每次最多读多少个Byte
                            byte[] buffer = new byte[size];//设置一个缓冲区
                            size = zipInputStream.Read(buffer, 0, buffer.Length);//从ZipInput流 读中读取内容,返回读取到的byte长度,
                            while (size > 0)//循环判断 ,如果size大于0  说明读到了内容
                            {
                                streamWriter.Write(buffer, 0, size);//将读到的内容写入目标文件(解压出来的文件)
                                size = zipInputStream.Read(buffer, 0, buffer.Length);//继续从ZipInput流 读中读取内容,返回读取到的byte长度
                            }
                        }
                    }
                }
            }
            return true;
        }
 

猜你喜欢

转载自www.cnblogs.com/lujingBK/p/11234501.html