C# 解压与压缩文件

 

解压文件 ,引用 SharpZipLib.dll类库

方法一:

  public void UnGzipFile(string zipfilename)
        {

            //同压缩文件同级同名的非压缩文件路径   
            var path = zipfilename.Replace(Path.GetFileName(zipfilename), Path.GetFileNameWithoutExtension(zipfilename));
            //创建压缩文件的输入流实例
            using (GZipInputStream zipFile = new GZipInputStream(File.OpenRead(zipfilename)))
            {
                //创建目标文件的流
                using (FileStream destFile = new FileStream(path, FileMode.Create))
                {
                    int buffersize = 2048;//缓冲区的尺寸,一般是2048的倍数
                    byte[] FileData = new byte[buffersize];//创建缓冲数据
                    while (buffersize > 0)//一直读取到文件末尾
                    {
                        buffersize = zipFile.Read(FileData, 0, buffersize);//读取压缩文件数据
                        destFile.Write(FileData, 0, buffersize);//写入目标文件
                    }
                    destFile.Flush();
                }
            }
        }

方法二:

        /// <summary>
        /// 引用 SharpZipLib.dll
        /// </summary>
        /// <param name="zipFilePath">压缩文件</param>
        /// <param name="filePath">解压文件</param>
        public void gunZipFile(string zipFilePath, string filePath)
        {
            using (Stream inStream = new GZipInputStream(File.OpenRead(zipFilePath)))
            {
                using (FileStream outStream = new FileStream(filePath, FileMode.Create))
                {
                    byte[] buf = new byte[4096];
                    StreamUtils.Copy(inStream, outStream, buf);
                }
            }
        }

 

压缩

        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="zipFilePath">压缩后的文件路径</param>
        public static void gZipFile(string filePath, string zipFilePath)
        {
            Stream s = new GZipOutputStream(File.Create(zipFilePath));
            FileStream fs = File.OpenRead(filePath);
            int size;
            byte[] buf = new byte[4096];
            do
            {
                size = fs.Read(buf, 0, buf.Length);
                s.Write(buf, 0, size);
            } while (size > 0);
            s.Close();
            fs.Close();
        }

 

文章来源:http://walkerqt.blog.51cto.com/1310630/1706239

 

posted @ 2017-08-25 15:45  逍遥帝君  阅读(872)  评论(1编辑  收藏  举报