c/c++语言开发共享c语言压缩文件详细讲解

目录c语言压缩文件话说当今压缩市场三足鼎立,能叫上名号的有zip、rar、7z。其中zip是压缩界的鼻祖,在各大平台上的流行度最广,rar是商业软件,压缩率和效率都是很高的,对个人用户没有限制。7z是

目录

c语言压缩文件

话说当今压缩市场三足鼎立,能叫上名号的有zip、rar、7z。其中zip是压缩界的鼻祖,在各大平台上的流行度最广,rar是商业软件,压缩率和效率都是很高的,对个人用户没有限制。7z是开源的,属于后起之秀,也有着不凡的压缩率,但在内存占有率的问题上,稍逊风骚。今天,主要总结下,windows平台下,zip的压缩与解压的方法,用icsharpcode组件。

一、单文件压缩

      场景,文件可能比较大,需要压缩传输,比如上传和下载

          /// <summary>           /// 单文件压缩          /// </summary>            /// <param name="sourcefile">源文件</param>            /// <param name="zipedfile">zip压缩文件</param>            /// <param name="blocksize">缓冲区大小</param>            /// <param name="compressionlevel">压缩级别</param>           public static void zipfile(string sourcefile, string zipedfile, int blocksize = 1024, int compressionlevel = 6)           {               if (!file.exists(sourcefile))              {                  throw new system.io.filenotfoundexception("the specified file " + sourcefile + " could not be found.");               }               var filename = system.io.path.getfilenamewithoutextension(sourcefile);                 filestream streamtozip = new filestream(sourcefile, filemode.open, fileaccess.read);               filestream zipfile = file.create(zipedfile);              zipoutputstream zipstream = new zipoutputstream(zipfile);                  zipentry zipentry = new zipentry(filename);               zipstream.putnextentry(zipentry);                 //存储、最快、较快、标准、较好、最好  0-9             zipstream.setlevel(compressionlevel);                  byte[] buffer = new byte[blocksize];                  int size = streamtozip.read(buffer, 0, buffer.length);               zipstream.write(buffer, 0, size);               try               {                   while (size < streamtozip.length)                   {                     int sizeread = streamtozip.read(buffer, 0, buffer.length);                      zipstream.write(buffer, 0, sizeread);                      size += sizeread;                  }              }               catch (exception ex)               {                  throw ex;               }              zipstream.finish();              zipstream.close();               streamtozip.close();           }      

说明:26行,blocksize为缓存区大小,不能设置太大,如果太大也会报异常。26-38行,把文件通过filestream流,读取到缓冲区中,再写入到zipoutputstream流。你可以想象,两个管道,一个读,另一个写,中间是缓冲区,它们的工作方式是同步的方式。想一下,能不能以异步的方式工作,读的管道只管读,写的管道只管写?如果是这样一个场景,读的特别快,写的比较慢,比如,不是本地写,而是要经过网络传输,就可以考虑异步的方式。怎么做,读者可以自行改造。关键一点,流是有顺序的,所以要保证顺序的正确性即可。

二、多文件压缩

      这种场景也是比较多见,和单文件压缩类似,无非就是多循环几次。

            /// <summary>            /// 多文件压缩           /// </summary>           /// <param name="zipfile">zip压缩文件</param>           /// <param name="filenames">源文件集合</param>           /// <param name="password">压缩加密</param>           public void zipfiles(string zipfile, string[] filenames, string password = "")           {                zipoutputstream s = new zipoutputstream(system.io.file.create(zipfile));                 s.setlevel(6);                if (password != "")                   s.password = md5help.encrypt(password);                  foreach (string file in filenames)               {                  //打开压缩文件                   filestream fs = file.openread(file);                     byte[] buffer = new byte[fs.length];                   fs.read(buffer, 0, buffer.length);                      var name = path.getfilename(file);                     zipentry entry = new zipentry(name);                   entry.datetime = datetime.now;                   entry.size = fs.length;                  fs.close();                   s.putnextentry(entry);                   s.write(buffer, 0, buffer.length);               }               s.finish();               s.close();           }  

说明:21行,缓冲区大小直接为文件大小,所以一次读完,没有循环读写。这种情况下,单个文件不能太大,比如超过1g。14行,可以为压缩包设置密码,

md5的生成方法如下:

      public class md5help      {          /// <summary>          ///32位 md5加密          /// </summary>          /// <param name="str">加密字符</param>          /// <returns></returns>          public static string encrypt(string str)          {              md5 md5 = new md5cryptoserviceprovider();                byte[] encryptdata = md5.computehash(encoding.utf8.getbytes(str));                return convert.tobase64string(encryptdata);          }      }       

三、多文件异步压缩

      上面同步的压缩的前提是,假设文件不大,而且文件数不多,但是现实是,不光文件大,而且文件数比较多。这种情况,就要考虑异步方法了。否则会阻塞主线程,就是我们平常说的卡死。

          /// <summary>          /// 异步压缩文件为zip压缩包          /// </summary>          /// <param name="zipfile">压缩包存储路径</param>          /// <param name="filenames">文件集合</param>          public static async void zipfilesasync(string zipfile, string[] filenames)          {              await task.run(() =>              {                  zipoutputstream s = null;                  try                  {                      s = new zipoutputstream(system.io.file.create(zipfile));                        s.setlevel(6); // 0 - store only to 9 - means best compression                         foreach (string file in filenames)                      {                          //打开压缩文件                           filestream fs = system.io.file.openread(file);                            var name = path.getfilename(file);                          zipentry entry = new zipentry(name);                          entry.datetime = datetime.now;                          entry.size = fs.length;                          s.putnextentry(entry);                            //如果文件大于1g                          long blocksize = 51200;                            var size = (int)fs.length;                            var oneg = 1024 * 1024 * 1024;                            if (size > oneg)                          {                              blocksize = oneg;                          }                          byte[] buffer = new byte[blocksize];                            size = fs.read(buffer, 0, buffer.length);                            s.write(buffer, 0, size);                            while (size < fs.length)                          {                              int sizeread = fs.read(buffer, 0, buffer.length);                              s.write(buffer, 0, sizeread);                              size += sizeread;                          }                          s.flush();                          fs.close();                      }                    }                  catch (exception ex)                  {                      console.writeline("异步压缩文件出错:" + ex.message);                  }                  finally                  {                      s?.finish();                      s?.close();                  }              });          }         

四、压缩文件夹

    实际的应用当中,是文件和文件夹一起压缩,所以这种情况,就干脆把要压缩的东西全部放到一个文件夹,然后进行压缩。

 主方法如下:

  /// <summary>          /// 异步压缩文件夹为zip压缩包          /// </summary>          /// <param name="zipfile">压缩包存储路径</param>          /// <param name="sourcefolder">压缩包存储路径</param>          /// <param name="filenames">文件集合</param>          public static async void zipfolderasync(string zipfile, string sourcefolder, string[] filenames)          {              await task.run(() =>              {                  zipoutputstream s = null;                  try                  {                      s = new zipoutputstream(system.io.file.create(zipfile));                        s.setlevel(6); // 0 - store only to 9 - means best compression                         compressfolder(sourcefolder, s, sourcefolder);                  }                  catch (exception ex)                  {                      console.writeline("异步压缩文件出错:" + ex.message);                  }                  finally                  {                      s?.finish();                      s?.close();                  }              });          }    

压缩的核心方法:

     /// <summary>            /// 压缩文件夹         /// </summary>           /// <param name="source">源目录</param>          /// <param name="s">zipoutputstream对象</param>           /// <param name="parentpath">和source相同</param>            public static void compressfolder(string source, zipoutputstream s, string parentpath)            {                string[] filenames = directory.getfilesystementries(source);               foreach (string file in filenames)              {                   if (directory.exists(file))                 {                       compressfolder(file, s, parentpath);  //递归压缩子文件夹                   }                   else                   {                       using (filestream fs = system.io.file.openread(file))                       {                           var writefilepath = file.replace(parentpath, "");                           zipentry entry = new zipentry(writefilepath);                           entry.datetime = datetime.now;                          entry.size = fs.length;                             s.putnextentry(entry);                              //如果文件大于1g                           long blocksize = 51200;                             var size = (int)fs.length;                             var oneg = 1024 * 1024 * 1024;                             if (size > oneg)                           {                               blocksize = oneg;                           }                           byte[] buffer = new byte[blocksize];                              size = fs.read(buffer, 0, buffer.length);                           s.write(buffer, 0, size);                                 while (size < fs.length)                           {                               int sizeread = fs.read(buffer, 0, buffer.length);                              s.write(buffer, 0, sizeread);                               size += sizeread;                           }                              s.flush();   //清除流的缓冲区,使得所有缓冲数据都写入到文件中                           fs.close();                       }                  }               }           }    

唯一需要注意的地方,可能解压出来的目录结构和压缩前的文件目录不同,这时候检查parentpath参数,它在zipentry实体new的时候用,替换绝对路径为当前的相对路径,也就是相对压缩文件夹的路径。

上面的方法比较复杂,还有一种相对简单的方式,直接调用api:

        public static string zipfolder(string sourcefolder, string zipfile)          {              string result = "";              try              {                  //创建压缩包                  if (!directory.exists(sourcefolder)) return result = "压缩文件夹不存在";                    directoryinfo d = new directoryinfo(sourcefolder);                  var files = d.getfiles();                  if (files.length == 0)                  {                      //找子目录                      var ds = d.getdirectories();                      if (ds.length > 0)                      {                          files = ds[0].getfiles();                      }                  }                  if (files.length == 0) return result = "待压缩文件为空";                  system.io.compression.zipfile.createfromdirectory(sourcefolder, zipfile);              }              catch (exception ex)              {                  result += "压缩出错:" + ex.message;              }              return result;          }    

以上就是c语言压缩文件详细讲解的详细内容,更多关于c语言压缩文件的资料请关注<计算机技术网(www.ctvol.com)!!>其它相关文章!希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

需要了解更多c/c++开发分享c语言压缩文件详细讲解,都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/791020.html

(0)
上一篇 2021年9月9日
下一篇 2021年9月9日

精彩推荐