. net file compression and decompression and Chinese folder name garbled problem

Source: Internet
Author: User
Tags getstream ziparchive

/************************** the blog content in the comment area to reference http://www.cnblogs.com/zhaozhan/archive/2012/05/28/2520701.html

Zip compression and decompression can be achieved in. NET in a variety of ways: 1, using SYSTEM.IO.PACKAGING;2, using a third-party class library, 3, through the System.IO.Compression namespace in the new ziparchive, ZipFile and other class implementations.

First, using System.IO.Packaging compression and decompression

The package is an abstract class that can be used to organize objects into a single entity in a defined physical format for portability and efficient access. The ZIP file is the main physical format of the package. Other package implementations can use other physical formats, such as XML documents, databases, or WEB services. Like the file system, the items contained in the package are referenced in folders and files in a hierarchical organization. Although the package is an abstract class, the Package.Open method uses the ZipPackage derived class by default.

System.IO.Packaging under the WindowsBase.dll assembly, you need to add a reference to WindowsBase when you use it.

1. Compress the entire folder into zip

<summary>///ADD a folder along with it subfolders to a package///</summary>// <param name= "FolderName" >the folder to Add</param>//<param name= "Compressedfilename" >the packa GE to create</param>//<param name= "overrideexisting" >override exsisitng files</param>/ <returns></returns> static bool Packagefolder (string folderName, String compressedfilename, bool ove rrideexisting) {if (Foldername.endswith (@ "\")) FolderName = Foldername.remove (folderName .            LENGTH-1);            BOOL result = FALSE; if (!            Directory.Exists (FolderName)) {return result;            } if (!overrideexisting && file.exists (compressedfilename)) {return result; } try {using (package = Package.Open (Compressedfilename, FileMode. Create) {var fileList = Directory.enumeratefiles (FolderName, "*", Searchoption.alldire                    Ctories);  foreach (String fileName in fileList) {//the path in the                        The subfolders after FolderName string pathinpackage; Pathinpackage = Path.getdirectoryname (fileName). Replace (FolderName, String.                        Empty) + "/" + path.getfilename (fileName);                        Uri parturidocument = Packurihelper.createparturi (new Uri (Pathinpackage, urikind.relative)); PackagePart packagepartdocument = package.                        CreatePart (Parturidocument, "", compressionoption.maximum);                            using (FileStream FileStream = new FileStream (FileName, FileMode.Open, FileAccess.Read)) {                        Filestream.copyto (Packagepartdocument.getstream ());         }           }} result = true;             } catch (Exception e) {throw new Exception ("Error zipping folder" + FolderName, E);        } return result; }

2. Add a single file to the zip file

<summary>//Compress a file into a ZIP archive as the Container Store//</summary> <param name= "FileName" >the file to compress</param>//<param name= "Compressedfilename" >Th E archive file</param>//<param name= "overrideexisting" >override existing file</param>/ <returns></returns> static bool PackageFile (string fileName, String compressedfilename, bool Overrid            eexisting) {bool result = false; if (!            File.exists (fileName) {return result;            } if (!overrideexisting && file.exists (compressedfilename)) {return result; The try {uri parturidocument = Packurihelper.createparturi (The new Uri (Path.get                               filename (filename), urikind.relative)); using (Package package = Package.Open (CompressedfilenAme, FileMode.OpenOrCreate)) {if (package. Partexists (parturidocument)) {package.                    Deletepart (parturidocument); } PackagePart packagepartdocument = package.                    CreatePart (Parturidocument, "", compressionoption.maximum);                        using (FileStream FileStream = new FileStream (FileName, FileMode.Open, FileAccess.Read)) {                    Filestream.copyto (Packagepartdocument.getstream ());            }} result = true;            } catch (Exception e) {throw new Exception ("Error zipping file" + FileName, E);        } return result; }

3. zip file Decompression

<summary>//Extract a container Zip. Note:container must be created as Open Packaging Conventions (OPC) specification//</summary>//// Lt;param name= "FolderName" >the folder to extract the package to</param>//<param name= "Compressedfile Name ">the package file</param>//<param name=" overrideexisting ">override existing files</param&        Gt <returns></returns> static bool Uncompressfile (string folderName, String compressedfilename, bool O            verrideexisting) {bool result = false; try {if (!                File.exists (Compressedfilename)) {return result;                } DirectoryInfo DirectoryInfo = new DirectoryInfo (folderName);                if (!directoryinfo.exists) directoryinfo.create (); using (Package package = Package.Open (Compressedfilename, FileMode.open, FileAccess.Read) {foreach (PackagePart PackagePart in package).                    GetParts ()) {Extractpart (PackagePart, FolderName, overrideexisting);            }} result = true; } catch (Exception e) {throw new Exception ("Error unzipping file" + Compressedfilen            Ame, E);        } return result;            } static void Extractpart (PackagePart packagepart, string targetdirectory, bool overrideexisting) { String Stringpart = TargetDirectory + Httputility.urldecode (packagePart.Uri.ToString ()).            Replace (' \ \ ', '/'); if (! Directory.Exists (Path.getdirectoryname (Stringpart))) Directory.CreateDirectory (Path.getdirectoryname (string            part));            if (!overrideexisting && file.exists (Stringpart)) return; using (FileStream FileStream= new FileStream (Stringpart, FileMode.Create)) {Packagepart.getstream ().            CopyTo (FileStream); }        }

Using the package archive will automatically generate a zip file [Content_type].xml, which describes the zip file to extract the supported file formats.

<?xml version= "1.0" encoding= "Utf-8"?> <types xmlns= "http://schemas.openxmlformats.org/package/2006/ Content-types ">    <default extension=" vsixmanifest "contenttype=" Text/xml "/>     <default Extension = "DLL" contenttype= "Application/octet-stream"/>     <default extension= "png" contenttype= "application/ Octet-stream "/>     <default extension=" txt "contenttype=" Text/plain "/>     <default Extension=" Pkgdef "contenttype=" Text/plain "/> </Types>

Similarly, if the zip file does not contain a [Content_type].xml file, or the [Content_type].xml] file does not contain a description of the extension (manually added [Content_type].xml is also possible), the file cannot be unzipped.

Ii. use of third-party class libraries

The zip compression and decompression uses are compared with sharpziplib and DotNetZip.

1, SharpZipLib, also known as "#ziplib", based on the GPL open source, support Zip,gzip,tar and BZIP2 compression and decompression.

Support for. NET 1.1,net 2.0 (3.5, 4.0).

(1) Zip compression

public static void Zip (String srcfile, string dstfile, int buffersize) {    FileStream filestreamin = new FileStream        ( Srcfile, FileMode.Open, FileAccess.Read);    FileStream filestreamout = new FileStream        (Dstfile, FileMode.Create, FileAccess.Write);    Zipoutputstream Zipoutstream = new Zipoutputstream (filestreamout);    byte[] buffer = new Byte<buffersize/>;    ZipEntry entry = new ZipEntry (Path.getfilename (srcfile));    Zipoutstream.putnextentry (entry);    int size;    Do    {        size = filestreamin.read (buffer, 0, buffer. Length);        Zipoutstream.write (buffer, 0, size);    } while (Size > 0);    Zipoutstream.close ();    Filestreamout.close ();    Filestreamin.close ();}

(2) Unzip the zip

public static void UnZip (String srcfile, string dstfile, int buffersize) {    FileStream filestreamin = new filestream
   
     (Srcfile, FileMode.Open, FileAccess.Read);    Zipinputstream Zipinstream = new Zipinputstream (filestreamin);    ZipEntry entry = Zipinstream.getnextentry ();    FileStream filestreamout = new FileStream        (dstfile + @ "\" + entry. Name, FileMode.Create, FileAccess.Write);    int size;    byte[] buffer = new Byte<buffersize/>;    Do    {        size = zipinstream.read (buffer, 0, buffer. Length);        Filestreamout.write (buffer, 0, size);    } while (Size > 0);    Zipinstream.close ();    Filestreamout.close ();    Filestreamin.close ();}
   

2, Dotnetlib, is based on "WS-PL" open source, the use of relatively simple
(1) compression

using (ZipFile zip = new ZipFile ()))  {    zip. AddFile ("ReadMe.txt");    Zip. AddFile ("7440-n49th.png");    Zip. AddFile ("2008_annual_report.pdf");            Zip. Save ("Archive.zip");  }

(2) Decompression

private void Myextract ()  {      string ziptounpack = "C1p3sml.zip";      String unpackdirectory = "extracted Files";      using (ZipFile zip1 = Zipfile.read (ziptounpack))      {          //here, we extract every entry, but we could extract Conditi Onally          //Based on entry name, size, date, checkbox status, etc.            foreach (ZipEntry e in zip1)          {            e.extract (unpackdirectory, extractexistingfileaction.overwritesilently);          }       }    }

Iii. compression and decompression using ziparchive, ZipFile and other classes in. NET 4.5

   static void Main (string[] args)        {            string zippath = @ "C:\users\exampleuser\start.zip";            String extractpath = @ "C:\users\exampleuser\extract";            String NewFile = @ "C:\users\exampleuser\NewFile.txt";            using (ziparchive Archive = Zipfile.open (Zippath, ziparchivemode.update))            {                Archive.createentryfromfile ( NewFile, "NewEntry.txt");                Archive.extracttodirectory (Extractpath);            }         }

***************************/

Bo Master of this use of compression method is quoted using Ionic.zip;

http://dotnetzip.codeplex.com/

The main problem is that the Chinese folder name garbled after compression

The specific code is as follows:

Folder path to be compressed string path1 = @ "D:\zhai\ Office"; System.Text.Encoding.Default solve the Chinese folder name garbled using (ZipFile ZF = new ZipFile (System.Text.Encoding.Default))            {                Zf. Adddirectory (path1);                Save path and compress file name after compression                ZF. Save (@ "D:\zhai\11.zip");            }

. net file compression and decompression and Chinese folder name garbled problem

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.