C # compressed file,

Source: Internet
Author: User
Tags crc32

C # compressed file,

I recently learned a truth, and I will share it with you here: Education represents your past, your present abilities represent your present, and learning represents your future.

Ten years in Hexi, do not bully teenagers poor.

There is no end to learning, keep improving

The previous section describes the Post request for passing parameters in C # WebApi-AJAX

This section discusses how to compress C # files and directly add the code

As follows:

Public class ZipUtility {// <summary> // cache all files /// </summary> List <string> files = new List <string> (); /// <summary> /// cache all empty directories /// </summary> List <string> paths = new List <string> (); /// <summary> /// compress a single file /// </summary> /// <param name = "fileToZip"> file to be compress </param> // /<param name = "zipedFile"> full name of the compressed file </param> // <param name = "compressionLevel"> compression degree, the value range is 0-9. The larger the value, the higher the compression program </param> // <param name = "B LockSize "> block size </param> public void ZipFile (string fileToZip, string zipedFile, int compressionLevel, int blockSize) {if (! System. IO. file. exists (fileToZip) // if The file cannot be found, The {throw new FileNotFoundException ("The specified file" + fileToZip + "cocould not be found. zipping aborderd ");} FileStream streamToZip = new FileStream (fileToZip, FileMode. open, FileAccess. read); FileStream zipFile = File. create (zipedFile); ZipOutputStream zipStream = new ZipOutputStream (zipFile); ZipEntry zipEntry = new ZipEntry (fileToZip); zipStre Am. putNextEntry (zipEntry); 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) {GC. collect (); throw ex ;} ZipStream. finish (); zipStream. close (); streamToZip. close (); GC. collect () ;}/// <summary> // compress the directory (including subdirectories and all files) /// </summary> /// <param name = "rootPath"> root directory to be compressed </param> /// <param name = "destinationPath"> Save path </param> /// <param name = "compressLevel"> compression degree, the value range is 0-9. The larger the value, the higher the compression program </param> public void ZipFileFromDirectory (string rootPath, string destinationPath, int compressLevel) {GetAllDirectories (rootPat H);/* while (rootPath. lastIndexOf ("\") + 1 = rootPath. length) // check whether the path ends with "\" {rootPath = rootPath. substring (0, rootPath. length-1); // If yes, remove "\"} * // string rootMark = rootPath. substring (0, rootPath. lastIndexOf ("\") + 1); // obtain the location of the current path to convert the compressed content into a relative path during compression. String rootMark = rootPath + "\"; // obtain the location of the current path to convert the compressed content into a relative path during compression. Crc32 crc = new Crc32 (); ZipOutputStream outPutStream = new ZipOutputStream (File. create (destinationPath); outPutStream. setLevel (compressLevel); // 0-store only to 9-means best compression foreach (string file in files) {FileStream fileStream = File. openRead (file); // open the compressed file byte [] buffer = new byte [fileStream. length]; fileStream. read (buffer, 0, buffer. length); ZipEntry entry = new ZipEntry (fil E. replace (rootMark, string. empty); entry. dateTime = DateTime. now; entry. size = fileStream. length; fileStream. close (); crc. reset (); crc. update (buffer); entry. crc = crc. value; outPutStream. putNextEntry (entry); outPutStream. write (buffer, 0, buffer. length);} this. files. clear (); foreach (string emptyPath in paths) {ZipEntry entry = new ZipEntry (emptyPath. replace (rootMark, string. empty) + "/"); outPu TStream. putNextEntry (entry);} this. paths. clear (); outPutStream. finish (); outPutStream. close (); GC. collect () ;}/// <summary> // obtain all the files and folders in the directory, save files and paths /// </summary> /// <param name = "rootPath"> root directory </param> private void GetAllDirectories (string rootPath) {string [] subPaths = Directory. getDirectories (rootPath); // obtain all the subdirectories foreach (string path in subPaths) {GetAllDirectories (path ); // The operation with the same root Directory: Find the subdirectory and save the file name of the current Directory to List} string [] files = Directory. getFiles (rootPath); foreach (string file in files) {this. files. add (file); // store the full names of all files in the current directory to the file List} if (subPaths. length = files. length & files. length = 0) // if it is an empty directory {this. paths. add (rootPath); // record the empty directory }}/// <summary> // decompress the file (the compressed file contains subdirectories) /// </summary> /// <param name = "zipfilepath"> path of the file to be decompressed </param> /// <param name = "unzippath"> extract specified object </Param> /// <returns> decompressed file List </returns> public List <string> UnZip (string zipfilepath, string unzippath) {// decompressed file List <string> unzipFiles = new List <string> (); // check whether the output directory ends with "\" if (unzippath. endsWith ("\") = false | unzippath. endsWith (": \") = false) {unzippath + = "\";} ZipInputStream s = new ZipInputStream (File. openRead (zipfilepath); ZipEntry theEntry; while (theEntry = s. getNextEn Try ())! = Null) {string directoryName = Path. getDirectoryName (unzippath); string fileName = Path. getFileName (theEntry. name); // generate the extract directory. [You do not need to create a directory when extracting data to the root directory of the hard disk.] if (! String. IsNullOrEmpty (directoryName) {Directory. CreateDirectory (directoryName);} if (fileName! = String. empty) {// if the file size is 0 after compression, it indicates that the file is Empty, so you do not need to read and write if (theEntry. compressedSize = 0) continue; // extract the file to the specified directory directoryName = Path. getDirectoryName (unzippath + theEntry. name); // create the following Directory and subdirectory Directory. createDirectory (directoryName); // record the exported file unzipFiles. add (unzippath + theEntry. name); FileStream streamWriter = File. create (unzippath + 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 ;}} streamWriter. close () ;}} s. close (); GC. collect (); return unzipFiles;} public string GetZipFileExtention (string fileFullName) {int index = fileFullName. lastIndexOf (". "); if (index <= 0) {throw new Exception (" The source package file is not a compress file ");} // extension string ext = fileFullName. substring (index); if (ext = ". rar "| ext = ". zip ") {return ext;} else {throw new Exception (" The source package file is not a compress file ");}}}

The above code is the method for compressing files. My test results are as follows:

This is the project source file. I want to compress the 45 worker compression files of the high-efficiency program. As shown in the figure, the compressed files are: 45 worker compression files of the high-efficiency program. ZIP files, but after you try to decompress this. ZIP file, you will find that the decompressed folder contains N + 1 layers of folders, and the compressed PDF file can be found in the last layer of folders, which is incredible, if you are interested, you can post your comments on the following comments for your reference. It also provides an idea for LZ. Thank you!

The sample code is as follows:

Public ActionResult Index () {C2Global. effecect. Common. ZipUtility zip = new C2Global. effecect. Common. ZipUtility (); zip. ZipFile (Server. MapPath ("~ /File/45 efficient programmers "), Server. MapPath ("~ /File/efficient Program Member's 452.16.zip "), 5, 10); return View ();}

Program Declaration: This program needs to reference a dll file. The full name of this dll file is ICSharpCode. SharpZipLib. dll. You can download it by yourself.

You can also try to download with this link: http://files.cnblogs.com/files/chenwolong/ICSharpCode.SharpZipLib.zip this is I uploaded to the blog Park, should be able to download, support Net4.5 framework

About: the folder obtained after decompression contains N + 1 layers of folders. please correct me and discuss it. Thank you!

@ Chen Wolong's blog

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.