1376
DotNetZip - Zip file manipulation in .NET languages DotNetZip is a small, easy-to-use class library for manipulating .zip files. It can enable .NET applications written in VB.NET, C#, or any .NET language, to easily create, read, and update zip files. Zip Compression is easy with DotNetZip. The DotNetZip project also includes a library for performing ZLIB, Deflate, or GZIP compression and decompression, a library for BZip2 compression and decompression, a GUI ZIP tool, and a few command line tools. DotNetZip works on Windows-powered PCs with the full .NET Framework, and also runs on Windows Mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language. The library can also be used from COM enironments, like PHP, Classivc ASP, or VBSCript. DotNetZip supports these scenarios: creating a zip archive, adding files or directories into the archive listing files in an archive, extracting files from an archive modifying an existing archive - renaming entries, removing entries from an archive, or adding new entries to an archive creating zip files from stream content, saving to a stream, extracting to a stream, reading from a stream dynamically creating ZIP files from ASP.NET or Silverlight applications If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, that is here, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams

DotNetZip - Zip file manipulation in .NET languages · DotNetZip - Zip file manipulation in .NET languages DotNetZip is a small, easy-to-use class library for manipulating .zip files

  • Upload
    dodiep

  • View
    333

  • Download
    1

Embed Size (px)

Citation preview

DotNetZip-Zipfilemanipulationin.NETlanguagesDotNetZipisasmall,easy-to-useclasslibraryformanipulating.zipfiles.Itcanenable.NETapplicationswritteninVB.NET,C#,orany.NETlanguage,toeasilycreate,read,andupdatezipfiles.ZipCompressioniseasywithDotNetZip.TheDotNetZipprojectalsoincludesalibraryforperformingZLIB,Deflate,orGZIPcompressionanddecompression,alibraryforBZip2compressionanddecompression,aGUIZIPtool,andafewcommandlinetools.

DotNetZipworksonWindows-poweredPCswiththefull.NETFramework,andalsorunsonWindowsMobiledevicesthatusethe.NETCompactFramework.CreateandreadzipfilesinVB,C#,orany.NETlanguage.ThelibrarycanalsobeusedfromCOMenironments,likePHP,ClassivcASP,orVBSCript.DotNetZipsupportsthesescenarios:

creatingaziparchive,addingfilesordirectoriesintothearchivelistingfilesinanarchive,extractingfilesfromanarchivemodifyinganexistingarchive-renamingentries,removingentriesfromanarchive,oraddingnewentriestoanarchivecreatingzipfilesfromstreamcontent,savingtoastream,extractingtoastream,readingfromastreamdynamicallycreatingZIPfilesfromASP.NETorSilverlightapplications

IfallyouwantisabetterDeflateStreamorGZipStreamclasstoreplacetheonethatisbuilt-intothe.NETBCL,thatishere,too.DotNetZip'sDeflateStreamandGZipStreamareavailableinastandaloneassembly,basedona.NETportofZlib.Thesestreams

supportcompressionlevelsanddelivermuchbetterperformancethatthebuilt-inclasses.ThereisalsoaZlibStreamtocompletetheset(RFC1950,1951,1952).

This100%managedcodelibrarycanbeusedinany.NETapplication-Console,Winforms,WPF,ASP.NET,Sharepoint,Webservicesapps,Powershellscripts,andsoon.ItproduceszipfilesthatarefullyinteroperablewithWindowsExplorer,aswellasJavaapplications,appsrunningonLinux.

Itisdesignedtobesimpleandeasytouse.DotNetZipispackagedasasingleDLL,about400kinsize.Ithasnothird-partydependencies.ItisMediumTrust,socanbeusedonmosthosters.GetzippingjustbyreferencingtheDLL.Thelibrarysupportszippasswords,Unicode,ZIP64,streaminputandoutput,AESencryption,multiplecompressionlevels,self-extractingarchives,andmore.

Thereleaseincludesthelibrary,aswellassomesampleapplications(withsource)showinghowtousethelibrary.

DotNetZipisDonationWare

IfyoufindDotNetZipuseful,considerdonating.Iamnowacceptingdonationsonbehalfofmyfavoritecharity.andYes,itisarealcharity.

http://cheeso.members.winisp.net/DotNetZipDonate.aspx

Copy

ExampleUsage

Example:creatingazipfile1 using(ZipFilezip=newZipFile("MyZipFile.zip")2 {3 zip.AddFile("c:\\images\\personal\\7440-N49th.png"4 zip.AddFile("c:\\Desktop\\2008-Regional-Sales-Report.pdf"5 zip.AddFile("ReadMe.txt");6 zip.Save();7 }

TonsmoreexamplesonCodeplex,andlaterinthishelpfile.

http://dotnetzip.codeplex.com/wikipage?title=Examples

FrequentlyAskedQuestions

HowdoesthisZipLibrarywork?DotNetZipispackagedasasingleDLL,asingleassembly.Itisfullymanagedcode,writteninC#,andprovidessupportforreadingandwritingZiparchivefilesandstreams.ThemaintypeisZipFile,featuringmethodslikeAdd(),Extract()andSave().TherearestringandintindexersfortheentriesoftheZipFile.Therearepropertiesforthingslikepasswordprotection,unicodeandcodepagesupport,andZIP64behavior.AndthereareprogresseventsforReading,Saving,andExtracting.

WhatdoIneed,inordertobeabletocreateandreadzipfilesfromwithinmyapplicationusingthislibrary?Tousethezipcapabilityinyourapplications,youneedtobeusingthe.NETFramework2.0orlater,andyouneedtheDotNetZipassembly.YoucanusetheZiplibraryfromanyapplication,whetheraconsoleapplication,aWindows-Formsapplication,aserver-basedapplicationlikeanASP.NETpage,orsomethingelse.YoucanuseC#,VB.NET,COBOL.NET,IronPython,IronRuby,F#,oranyother.NETlanguage.

WhatdoIneedtobuildthislibraryfromthesource?Tousethezipcapabilityinyourapplications,youneedtobeusingthe.NETFramework2.0orlater,andyouneedtheDotNetZipassembly.YoucanusetheZiplibraryfromanyapplication,whetheraconsoleapplication,aWindows-Formsapplication,aserver-basedapplicationlikeanASP.NETpage,asmart-deviceapp,aWindowsService,orsomethingelse.YoucanuseC#,VB.NET,COBOL.NET,IronPython,IronRuby,F#,oranyother.NETlanguage.YoucanusethefullversionofVisualStudio,oroneoftheVisualStudioExpresstools,orjustatexteditor.

WhatifIjustwanttousethegraphicaltool?

Noproblem.JustdownloadtheUtilsdownloadfromthelatestreleasestab,andyouwillgetaneasy-to-usefully-functionalZIPcreationandextractiontool,afreefunctional-equialentreplacementforWinZip.ItsupportsalltheDotNetZipcapability,likeSFX,AES,ZIP64,arbitraryCodePages,Unicode,zipcomments,fileandentryselection,andmore.

WhatdoIneedto_build_thislibraryfromthesource?fYouneedthe.NETFrameworkSDKv3.5,orlater;or,VisualStudio2008orlater.Whilethelibraryisusableby.NET2.0andlater,tobuildityouneed.NET3.5orlater.ThisisbecausethesourcecodeusesfeaturesthatwereintroducedintheC#v3.0compiler,varsandarrayinitializersandsoon.The.NET3.5SDKisavailablehere.Idon'tknowifthelibrarywill_build_inVisualC#Express2008;Inevertriedit.Itshould.

Howbigisthelibrary?Asofversion1.9,theIoniczipDLLisabout420kinsize.Theself-extractingcapabilitycomprisesabout200kofthat.Thereisa"Reduced"buildofthelibraryintheDeveloper'sKit,thateliminatestheSFXcapabilityandresultsinaDLLofabouthalfthesize.TheCompact-Frameworkversionofthelibraryisabout130k.ThereisjustoneDLL.Thereisnootherpre-requisite.

WhywouldyouwanttoproduceyetanotherZipLibrary?Thereareanumberofoptionsinthe.NETworldformanipulatingzipfiles.Somearecommerciallibraries,someareopen-source.Youcanevenshoe-horntheSystem.IO.PackagingAPI,whichisincludedin.NET3.0,intoaziplibrary.Buttherearetradeoffsforallofthem.Somepeoplearewillingtogiveupcommercialsupportforalowerprice.Somepeopledon'tliketheGPL.Someofthoseotherpackagesarecomplextouseforzipfiles.Someofthemdon'thaveenoughfeatures(Eg,AESencryption,ZIP64).Somearetooslow.WhatI

http://www.microsoft.com/downloads/details.aspx?FamilyID=e6e1c3df-a74f-4207-8586-711ebe331cdc&DisplayLang=en

foundisthatmostpeoplewantsomethingsimpleandeasytouse,thatworkswell,hasgoodfeatures,compresseseffectivelyandfast,andistherightprice.DotNetZipisthatoption.It'sfast,it'ssimple,it'sfree.

Doesthislibrarymakeself-extractingzipfiles?Yes.Itcanmakeself-extractingzipfilesorstandardzipfiles.Theself-extractingarchivescaneitherbeWindows(GUI)appsorcommand-lineapplications.Theself-extractorsrequire.NET2.0onthecomputerdoingtheextraction.

Doesthislibraryreadself-extractingzipfiles?Yes.Asofv1.7,DotNetZipcanreadself-extractingzipfilesgeneratedbyWinZip.Asofv1.8(currentlyinpreview),DotNetZipcanreadSFXarchivesgeneratedbyitself.DotNetZipdoesnot(yet)readSFXarchivesbuiltbysomeothertools.I'venottestedit.

Arethezipfilesthislibrarymakescompatiblewiththejava.util.zipclassesintheJavaclasslibrary?Yes.Thislibrarymakesstandardzipfiles.Ifyouusesomeadvancedfeaturesnotsupportedbythebuilt-inJavalibrary,likeAESencryptionorZIP64,thenthezipfileswon'tbereadablebyJava.ThisisashortcominginJava,notinDotNetZip.

IfIcreateazipfilewiththislibrary,canIopenitfromwithinaJava/PHP/Python/C/Perlapplication?FromwithinWinRar/WinZIP?Yes.Thislibrarymakesstandardzipfiles,soanythingthatcanreadandwritezipfiles,onanyplatform,canworkwithzipfilesgeneratedfromthislibrary.InJava,youwouldusethejava.util.ziplibrary.InPython,youwouldusethezipfilemodule.KeepinmindthatnotalllanguagesandenvironmentssupportallZIPfeatures.Forexample,currentlytheJavalibrarydoesnotdoZIP64,andthezipfilemoduleinPythondoesnotsupportzipfilecomments,whileDotNetZipcancreateandreadziparchivesusingthosefeatures.Youneedtobe

carefulwithinteroptesting.Ifyoudon'tknowwhatthesefeaturesare,youprobablydon'tneedthemandyouwon'trunintointeropproblems.

IfIcreateazipfilewithajava/PHP/Python/C/Perlapplication,orwithWinRar/WinZip/7zip,canIopenitfromwithina.NETapplication,usingthislibrary?Yes.Thislibraryreadscompliantzipfiles.

CanIuseWindowsExplorertoopenthezipfilesthatthislibrarycreates,andviceversa?Yes.Thislibraryreadsandwritesstandardzipfiles.IfyouuseextensionstotheZIPspecnotsupportedbyWindows,likeZIP64orAESencryption,WindowsExplorerwillnotbeabletoextractthefiles.

Doesthelibraryworkwithapplicationsthatdependonthe.NETCompactFramework?Yes.DotNetZipisbuiltforthe.NETCompactFramework(v2.0orlater)aswellasfortheregular.NETFramework(v2.0orlater).ThismeansyoucanbuildaSmartDeviceapplicationinVisualStudio2008,thatusesthecapabilitiesofDotNetZip.

Doesthelibrarysupportzero-lengthzipentries,zipfilecomments,zipentrycomments,zippingupemptydirectories,recursivedirectorytraversal,zippingupselectedfilesbyfilename(withwildcards),andpassword-protectingentries?Yes.

DoesthelibraryhandleZIP64?Yes.ThiswasaddedinDecember2008inv1.7.TheoriginalZIPspecificationallowedupto65535entriesinaziparchive,andarchiveandentrysizesupto4.2g.TheZIP64extensionsraisethoserestrictions,attheexpenseofcompatibilityandinteroperability.

DotNetZipcanreadorwrite"standard"zipfilesorZIP64zipfiles.

Doesthislibrarysupportanycompressionalgorithmotherthandeflate?No.EntriesareeitherStoredorDeflated.

DoesthislibraryuseSystem.IO.Compression.DeflateStreamfortheDEFLATEalgorithm?No.Inearlierversions,itdid.ButtheDeflateStreambuilt-intothe.NETFrameworkBCLexhibitsanomalouscompressionbehavioronpreviouslycompresseddata,likemp3orjpgfiles.DotNetZipincludesamanagedcompressionlibrary,basedonZLIB.It'sfast,fullyDEFLATEcompliant,anditcompressesbetterthanthebuiltinversion!And,theDeflateStreamthatisincludedinDotNetZipisavailableforanyapplicationtouse,underthesametermsastherestoftheDotNetZiplibrary.

WhywouldadevelopernotjustusethePackagingAPIsincludedinthe.NETFramework3.0?ThePackagingAPIsareoptimizedforproducing.docxfilesand.xlsxfiles.Thislibraryisgenerallysimplerandcleanerforcreatingorreadingplain,genericzipfiles.AlsothislibrarytakesadvantageofZIPfeatureslikeZIP64orAES,inamuchnicerway.Anditprovidesnicefeatureslikeprogresseventsandfileselectors.

Doesthelibrarysupportreadingorwritingencryptedorpasswordprotectedzipfiles?Yes,thislibraryhelpsapplicationsreadandwritezipfilesthatusepasswordstoprotecttheentriesintheziparchive.EitherPKZIP("weak")encryptionorWinZip-compatibleAESencryption.

CanWindowsExplorer("compressedfolders")readandextractthezipfilescreatedbythislibraryiftheziphaspasswordprotection?

Yes.Itjustworks.

CanIusetheDotNetZiplibrarytoread.docxfiles,.xslxfiles?Yes.Theyarejustzipfiles.Keepinmind,thePackagingAPIsincludedin.NET3.0areoptimizedforproducing.docxfilesand.xlsxfiles.

DoesthelibrarysupportUnicodefilenamesandcomments?Yes,asofSeptember2008,thelibrarycancreateandreadzipfilesthathaveUnicode(UTF-8)filenamesandcomments.Youcanalsospecifyarbitrarycodepageswhenreadingorwritingzipfiles.But,WindowsExplorerdoesnotsupportUTF-8encodedzipfiles.Toreadthezipyoucreate,youwillhavetouseatoolorlibrarythatsupportsunicode,suchasWinRar,DotNetZip,etc.

CanthelibrarybeusedtoreadazipfilethathasentrieswithfilenamescontainingChinesecharacters,asproducedbyWinRAR?Yes.Todothisyouwouldspecifythe"big5"codepage(cp950)whenreadingthezip.InadditiontoChinese,itcanhandleanycodepage.

Whataboutreadingandwritingzipfileswithotherlanguagesandcodepages?Portugese?Hebrew?Arabic?Greek?Cyrillic?Norwegian?Finnish?etc?Yes.Justspecifytheappropriatecodepagewhenreadingorwritingtheziparchive.

CanWindowsExplorer("compressedfolders")readthezipfilescreatedbythislibraryiftheziphasentrieswithUnicode-encodedfilenames?No.ButthatisalimitationofWindowsXPandWindowsVista.Itisnotalimitationofthislibrary.

Istheredocumentationforthelibrary?

Yes,thereisaCHMfileinMSDNhelpfileformat,generatedfromthexmlcommentsinthecode.Allthepublicinterfacesarethoroughlydocumented.Therearetonsofcodeexamplesinthedoc.

Doesthelibrarysupportzippingtoastream?Orunzippingfromastream?Yes,youcanzipupfilesandSavetheziparchivetoastream.AswellyoucanReadaziparchivefromanopenstream-Iusethisforembeddedresourcesinapps:IcallGetManifestResourceStream(),andthenunzipthatresource.ReadingandwritingstreamscomplementsthecapabilityofbeingabletoSavetoaplainfileorreadfromaplainfile.TheSave-to-a-streamcapabilityallowsyoutowriteaziparchiveoutto,forexample,theASP.NETResponse.Outputstream,withoutcreatinganintermediatefile.VeryniceforASP.NETapplications.

Ok,thelibrarycanwriteaziparchivetoastream,andreadazipfromastream,But...canthelibraryaddanentrytoazipfile,grabbingcontentfromastream?canthelibraryunzipasingleentryintoastream?Cananapplicationreadanentryasastream?Yes.Yes.Yes.Unlikesomeotherlibraries,inmostcasesDotNetZiphandlesthestreaming;yourapplicationdoesnotneedtoimplementaRead/Writedatapump.Theapplicationneedsonlytoopenthestreams.Usingthestreamsupport,youcould,forexample,openaziparchive,andthenmodifythefilesinthearchive,andSaveouttoaResponse.OutputStreaminASP.NET,withouteverwritingafiletothedisk.Allthezipfilecontentcanbemaniulatedinmemory(usingMemoryStreamforexample).

Doesthislibraryallowremovalofentriesfromzipfiles,orupdatingofentriesinzipfiles?Yes.

DoIhavetowriteprogramstotakeadvantageofthisthing?oris

theresomeotherwayIcantakeadvantageoftheDotNetZip?TypicallypeoplewillembedthisDLLintoanapplication.But,theDotNetZipdownloadsincludesapackageof"example"applications:command-lineutilitiesthatutilizethelibrary,thatyoucanuseoutoftheboxtozipandunzip.Idroptheseinmyownbindirectoryanditallowsmetozipandunzipfromthecommandlineorfrombatchfiles.Also,youcantakeadvantageoftheDotNetZiplibraryfromwithinPowershell,ifthatisyourbag.Creatingorextractingzipswithinascriptisprettyhandy.

CanIgrabthesourceforDotNetZipandembeditintomyownproject?Yes-that'sallowedbythelicense.ButyoumaywanttothinkaboutjustredistributingthebinaryDLL-itisamucheasieroption.

CanIdistributethebinaryDLLwithmyownproject?Yes-that'sallowedbythelicense.

What'sthemainstreamapproachforusingDotNetZipina3rdpartyapp?ThemainstreamapproachistodistributethebinaryDLLwithyourownapp.

WhatifIwanttouseDotNetZipinmyapp,butIdon'twanttodistributeitasaseparateDLL?Youhaveoptions.ThemostmainstreamandgenerallyeasiestwaytoembedDotNetZipintoyourapplicationistoredistributetheDLL.Butifyoudon'twanttodothat,therearealternatives.OneoptionistoembedthesourceforDotNetZipintoyourownproject.Thismayseemliketheobviousapproach,butitisprobablynotwhatyouwant,unlessyoureallyneedtomodifythesourceofDotNetZip.AbetterapproachistomergetheDLLintoyourEXE,withILMerge.Thisworkswithyourappregardlessofwhatlanguageituses,whetheritisaWinformsapp,aWPFapp,aservice,etc.

http://www.microsoft.com/downloads/details.aspx?familyid=22914587-b4ad-4eae-87cf-b14ae6a939b0&displaylang=en

GettingStartedwithDotNetZipThispagedescribeshowtogetstartedusingDotNetZip.

Whichdownloadtochoose?

DotNetZipisfreetouse.Youjustneedtodownloaditandstartusingit.DifferentdownloadsofDotNetZipareavailable.Whichoneyouchoosedependsonwhatyouwanttodo.

Ifyourgoalis... Downloadthis... whichcontains...

Toreadthedocumentationforthelibraryandtools

DotNetZipLib-*.chm

acompiledhelpfilecontainingallthedocumentation.

Tobuild.NET,COM,orPowerShellappsthatusetheZiplibrary.

DotNetZipLib-DevKit-vx.x.zip

thesignedDLLsforZipandZlib,forboththedesktopandCompactFramework;theXMLDocumentationfileforintellisense;thecompiledhelpfile(CHM);anMSIfilethatinstallshelpintoVisualStudio;andtheLicense.

TomodifyorviewthesourcecodefortheZip&ZlibLibraries,thesetup(msi)project,ortheexamples.

DotNetzip-src-vx.x.x.x.zip

theVS2008solution,containinganumberofVSprojectsandthesourcecodeforthelibraryandvariousexamplesthatusethelibrary.

Todistribute.NETapplicationsthatusetheZiplibrary,orifyouwanttoruna.NETapplicationthatdependsonthislibrary.

DotNetZipLib-Runtime-vx.x.zip

thesignedDLLsforZipandZlib,forboththedesktopandCompactFramework;andtheLicense.ThisisastrictsubsetoftheDevKitdownload.

Todistribute.NETapplicationsthatusetheZiplibrary,orifyouwanttoruna.NETapplication

DotNetZipLib-Runtime-vx.x.msi

an.MSIversionoftheRuntimerelease,containingsignedDLLsforZipandZlib,forboththedesktopandCompactFramework;

http://dotnetzip.codeplex.com/Release/ProjectReleases.aspx

thatdependsonthislibrary.

andtheLicense.

Tocreate,read,ormodifyZIPfilesfromwithinaWindowsGUIinterface,orfromthecommandline,orfromwithinbatchfiles.

DotNetZipUtils-v1.8.zip

asetofexetools(command-lineandGUI)thatrelyontheDotNetZiplibrary,tocreateandmanagezipfiles.

Tocreate,read,ormodifyZIPfilesfromwithinaWindowsGUIinterface,orfromthecommandline,orfromwithinbatchfiles.

DotNetZipUtils-v1.8.msi

an.MSIversionoftheUtilsdownload.Thisinstallsasetofexetools(command-lineandGUI)thatrelyontheDotNetZiplibrary,tocreateandmanagezipfiles.There'salsoanuninstaller.

WhichDLLtouse?

WhenyouarebuildinganapplicationthatmanipulatesZIPfiles,youwillwanttouseoneofthebinaryreleasesofDotNetZip.ThesereleasesincludemultipledistinctDLLsorassemblies.Whichoneshouldyouuse?

Thelikelyansweris:Ionic.Zip.dll

That'sthemainstreamlibrary,thefulllibrary,anditincludesallthecapabilityofDotNetZip.TheotherDLLsarereducedinvariousways,tosuiteparticularrequirements.

Forexample,youmaywantasmallerlibrary,oryouwanttoexcludetheSelf-Extractingcapability,oryouonlywanttheZLIBcapability.Inthesecases,youmaywanttochooseadifferentassembly.

Here'sasummaryoftheoptions.

Usagescenario DLLBasicreadingorwritingofZipfiles Ionic.Zip.dllrawblockorstreamcompressionusingZLIB,DEFLATE,orGZip Ionic.Zlib.dll

compressionusingtheBZip2algorithm Ionic.BZip2.dllSomecombinationofZLIB/DEFLATE/GZIPcompression,BZip2compression,andreadingorwritingZipfiles

Ionic.Zip.dll

readingorwritingZipfileson.NETCompactFramework Ionic.Zip.CF.dll

ZLIB/DEFLATE/GZIPcompressionon.NETCompactFramework Ionic.Zlib.CF.dll

compressionusingtheBZip2algorithmon.NET Ionic.BZip2.CF.dll

CompactFrameworkSomecombinationofZLIB/DEFLATE/GZIPcompression,BZip2compression,andreadingorwritingZipfileson.NETCF

Ionic.Zip.CF.dll

readingorwritingZipfiles,butnevercreatingaself-extractingarchive Ionic.Zip.Reduced.dll

TherearealsoSilverlightversionsoftheZlib,BZip2,andZiplibraries.

NeverreferencebothIonic.Zlib.dllandIonic.Zip.dllinthesameapplication,orbothIonic.BZip2.dllandIonic.Zip.dll.IfyourapplicationdoesbothZlibandZipthings,orbothBZip2andZipthings,orallthree,youneedonlyaddareferencetoIonic.Zip.dll.Ionic.Zip.dllincludesallthecapabilityinIonic.Zlib.dllandIonic.BZip2.dll.YoualwaysneedtoreferenceonlyasingleIonicDLL,regardlesswhetheryouuseZliborBZip2orZiporsomecombination.

IfyouuseCOM,thenyouwanttoreferencethemainDLL,Ionic.Zip.dll.IfyouinstalltheDotNetZipRuntimelibraryviathe.MSIinstaller,thecorrectDLLwillautomaticallybeinstalledandregisteredforusewithCOM.Ifyoudon'tusethe.MSIinstaller,youwillhavetoperformthesestepsyourself.ConsultthedocumentationonusingDotNetZipwithCOMformoreinformation.

DotNetZipworkswiththe.NETCompactFrameworkThereisaspecialversionofDotNetZip,specificallybuiltforthe.NETCompactFrameworkv2.0orv3.5.

TheprogrammingmodelisexactlythesameasfortheregularDotNetZiplibrary.ThereareafewfeaturesnotsupportedintheCFversionofDotNetZip:

1. Self-extractingarchives.TheZipFile.SaveSelfExtractor()methodisnotavailableintheCFversionofDotNetZip.There'snostrongtechnicalreasonforthislimnitation;Ijustdidn'tthinkitwouldbeofmainstreaminterest,andinordertokeepthesizeofthelibrarydown,IomittedthatpartfromtheCFversion.Itamountstoabouta120ksavings.

2. WinZipAESencryption.TheCFversiondoesnotsupportencryptionusingWinZipAes128orWinZipAes256.Thisisbecausethecryptoclassesfromthe.NETFrameworkarenotavailableon.NETCF.IwouldhavetowritemyownSHA1HMAC()andsoon,whichIhaven'tgot'roundtodoing,especiallybecausenooneisclamoringforit.

3. ParallelDeflateStream.Mostmobiledevicesdonotusemulticoreprocessors,soaparalleldeflaterwouldoffernobenefit.Evenasidefromthat,paralleldeflationshowsitsstrengthwhencmopressinglargerfiles,andwhenlargermemoryresourcesareavailable.Bothoftheseareunlikelyin.NETCFapplications.

UsingDotNetZipinaSmartDeviceproject

TobuildasmartdeviceapplicationthatusesDotNetZip,youwillneedtouseVisualStudio2008orlater.

1. OpenVisualStudio2008.2. Createasmartdeviceproject.Specifythatitwillusethe.NET

CompactFrameworkv2.0orv3.5.3. AddaReferencetotheCFLibraryforDotNetZip.Thefilename

isIonic.Zip.CF.dll4. Buildyourapplicationasnormal.

AbouttheProjectDesign

IfyouareadeveloperwhowantstomodifyorextendtheDotNetZiplibraryitself,thefollowingmaybeofinterest.

TheCF-LibraryprojectintheDotNetZipsourcedistributionincludesallofthesourcefilesasLinkstotheoriginalfilesintheLibraryproject.Thismeans,thesourcefilesarenotduplicated.Anychangesneedtobemadeonlyonce.TheCF-Libraryprojectissimplya"buildproject"inthatregard.Thereisnoadditionalsourcecodespecificallyforthe.NETCompactFramework.

NETCFisdefinedasaconditionalcompilesymbolfortheCF-Libraryproject.Thissymbolisusedinthesourcetoexcludecodethatwillnotrunonthe.NETCompactFramework,forexample,thecallstoSetLastModifiedTime()methodontheSystem.IO.Fileclass.

Copy

Copy

DotNetZip-C#ExamplesHereareabunchofexamplesinC#thatillustratehowtousethelibrary.

Thereareafewcomplete,workingexampleapplicationsshippedinthesourcecodedistribution.

Createazipfile,andadditemstoit.

AddItems11 using(ZipFilezip=newZipFile())2 {3 zip.AddFile("ReadMe.txt");4 zip.AddFile("Resume.doc");5 zip.AddFile("Portrait.png");6 zip.Save("Package.zip");7 }

Additemstoazipfile,usingZip2.0encryption,andthesamepasswordforallitems.

AddItems21 using(ZipFilezip=newZipFile())2 {3 zip.Password="123456!";4 zip.AddFile("ReadMe.txt");5 zip.AddFile("7440-N49th.png");6 zip.AddFile("2005_Annual_Report.pdf");7 zip.Save("Backup.zip");8 }

Copy

Copy

Addfilestoazipfile,usingZip2.0encryption,anddifferentpasswordsfordifferentfiles.

Additems31 using(ZipFilezip=newZipFile())2 {3 zip.AddFile("ReadMe.txt");//nopasswordforthisone4 zip.Password="123456!";5 zip.AddFile("7440-N49th.png");6 zip.Password="!Secret1";7 zip.AddFile("2005_Annual_Report.pdf");89 zip.Save("Backup.zip");10 }

Createaziparchive,andaddfilestoit,usingWinZip-compatibleAES256-bitencryptionforoneofthefiles.

Additems41 using(ZipFilezip=newZipFile())2 {3 zip.AddFile("ReadMe.txt");//nopasswordforthisone4 zip.Password="Cool.Hand.Luke!";5 zip.Encryption=EncryptionAlgorithm.WinZipAes256;6 zip.AddFile("Rawdata-2008-12-18.csv");7 zip.Save("Backup-AES-Encrypted.zip");8 }

Createazip,andaddafile,tellingthelibrarytonotusecompressionwhenaddinginthefile.Thismakessensewithpreviously-compressedfilessuchasthosein.mp3format.TheDeflatealgorithmcanactually

Copy

Copy

Copy

increasethesizeofadatastreamthathasalreadybeencompressed.TheDotNetZiplibraryintelligentlyturnsoffcompressionforthosefilesthatgetbiggerwithcompression,buttheForceNoCompressionpropertyallowsyoutodoitexplicitly.

NoCompression1 using(ZipFilezip=newZipFile())2 {3 zip.ForceNoCompression=true;4 zip.AddFile(@"MyMusic\Handel\Messiah-01.mp3");5 zip.Save(ZipFileToCreate);6 }

Zipupanentiredirectory,recursively.Useunicodetoencodeentriesinthearchive,forthosefilesinthatdirectorytreethathavecharactersoutsidetheANSIrange.Finally,specifyacommentontheziparchivewhencreatingit.(BecarefulusingUnicode-itisnotwidelysupportedbyotherziputilities)

Zipadirectory1 using(ZipFilezip=newZipFile())2 {3 zip.UseUnicode=true;//utf-84 zip.AddDirectory(@"MyDocuments\ProjectX");5 zip.Comment="Thiszipwascreatedat"+System.DateTime.Now.ToString(6 zip.Save(ZipFileToCreate);7 }

Zipupanentiredirectory,recursively.Usethe"big5"encodingforthosefilesinthatdirectorytreethathavechinesecharacters.

Zipadirectory2

Copy

Copy

1 using(ZipFilezip=newZipFile())2 {3 zip.Encoding=System.Text.Encoding.GetEncoding("big5"4 zip.AddDirectory(@"MyDocuments\ProjectX");5 zip.Save(ZipFileToCreate);6 }

Zipupanfile,usingtheZIP64extensionsifnecessarytosupportlargefiles.

Zip641 using(ZipFilezip=newZipFile())2 {3 zip.UseZip64WhenSaving=Zip64Option.AsNecessary;4 zip.AddFile(@"RawData-HugeFile-13800.dat");5 zip.Save(ZipFileToCreate);6 }

Zipupasetoffiles,eachprotectedbythesamepassword.Also,explicitlyoverridethelastmodifiedtimeforallofthefilesastheyarestoredintheziparchive.

SetLastModifiedtime1 23

Zipupasetoffilesanddirectories,andre-mapthemintoa4 differentdirectoryhierarchyinthezipfile.

56 8 using(ZipFilezip=newZipFile())9 {

Copy

Copy

10 //filesinthefilesystemlikeMyDocuments\ProjectX\File1.txt,willbestoredintheziparchiveasbackup\File1.txt11 zip.AddDirectory(@"MyDocuments\ProjectX","backup"12 //filesinthefilesystemlikeMyMusic\Santana\OyeComoVa.mp3,willbestoredintheziparchiveastunes\Santana\OyeComoVa.mp313 zip.AddDirectory("MyMusic","tunes");14 //TheReadme.txtfileinthefilesystemwillbestoredintheziparchiveasdocuments\Readme.txt15 zip.AddDirectory("Readme.txt","documents");1617 zip.Comment="Thiszipwascreatedat"+System.DateTime.Now.ToString(18 zip.Save(ZipFileToCreate);19 }

Addcontentobtainedfromastream(MemoryStrean,FileStream,etc)intoaziparchive.Also,addacommenttotheentrythatwasaddedfromthestream.

Streams1 using(ZipFilezip=newZipFile())2 {3 ZipEntrye=zip.AddEntry("Content-From-Stream.bin"4 e.Comment="Thecontentforentryinthezipfilewasobtainedfromastream"5 zip.AddFile("Readme.txt");6 zip.Save(ZipToCreate);7 }

Openanexistingzipfile,removeanentryfromit,andsavethearchive.Thiswasfirstsupportedinv1.5ofthelibrary.

Removeanentry1 using(ZipFilezip=ZipFile.Read(ExistingZipFile))2 {3 //usetheindexertoremovethefilefromtheziparchive4 zip["Readme.txt"]=null;5 zip.Comment="Thisarchivehasbeenmodifiedfromitsoriginalversion.Somefileshavebeenremoved."

Copy

Copy

6 zip.Save();7 }

Openanexistingzipfile,renameanentry,thensaveit.Thiswasfirstsupportedinv1.7ofthelibrary.

Rename1 intrenameCount=0;2 using(ZipFilezip2=ZipFile.Read(ExistingZipFile))3 {4 foreach(ZipEntryeinzip2)5 {6 if(e.FileName.EndsWith(".txt"))7 {8 varnewname="renamed_files\\"+e.FileName;910 e.FileName=newname;11 e.Comment="renamed";12 renameCount++;13 }14 }15 zip2.Comment=String.Format("Thisarchivehasbeenmodified.{0}fileshavebeenrenamed."16 zip2.Save();17 }

Extractallfilesfromaziparchive:

Extract11 using(ZipFilezip=ZipFile.Read(ExistingZipFile))2 {3 foreach(ZipEntryeinzip)4 {5 e.Extract(TargetDirectory);

Copy

Copy

Copy

6 }7 }

ThedefaultbehaviorofextractionistoNOToverwriteexistingfiles.Inthisexample,theappExtractsallfiles,andoverwritesexistingfilesinthefilesystem:

Extract21 using(ZipFilezip=ZipFile.Read(ExistingZipFile))2 {3 foreach(ZipEntryeinzip)4 {5 e.Extract(TargetDirectory,true);//overwrite==true6 }7 }

Extractanentryfromtheziparchiveintoapreviously-openedstream:

Extract31 using(ZipFilezip=ZipFile.Read(ExistingZipFile))2 {3 ZipEntrye=zip["MyReport.doc"];4 e.Extract(OutputStream);5 }

ExtractanEntrythatwasencryptedwithapassword,intothespecifiedbasedirectory:

Extract41 using(ZipFilezip=ZipFile.Read(ExistingZipFile))2 {

Copy

3 ZipEntrye=zip["TaxInformation-2008.xls"];4 e.ExtractWithPassword(BaseDirectory,Password);5 }

Listalltheentriesinazipfile:

List11 using(ZipFilezip=ZipFile.Read(ExistingZipFile))2 {3 foreach(ZipEntryeinzip)4 {5 if(header)6 {7 System.Console.WriteLine("Zipfile:{0}",zip.Name);8 if((zip.Comment!=null)&&(zip.Comment!=9 System.Console.WriteLine("Comment:{0}",zip.Comment);10 System.Console.WriteLine("\n{1,-22}{2,8}{3,5}{4,8}{5,3}{0}"11 "Filename","Modified"12 System.Console.WriteLine(newSystem.String('-'13 header=false;14 }15 System.Console.WriteLine("{1,-22}{2,8}{3,5:F0}%{4,8}{5,3}{0}"16 e.FileName,17 e.LastModified.ToString(18 e.UncompressedSize,19 e.CompressionRatio,20 e.CompressedSize,21 (e.UsesEncryption)?"Y"2223 }24 }

Readinziparchivecontentfromastream,andextractthecontentfor

Copy

Copy

oneentrytoanotherstream.Inthisexample,thefilename"NameOfEntryInArchive.doc",refersonlytothenameoftheentrywithintheziparchive.Afilebythatnameisnotcreatedinthefilesystem.TheI/Oisdonestrictlywiththegivenstreams.

Stream11 using(ZipFilezip=ZipFile.Read(InputStream))2 {3 zip.Extract("NameOfEntryInArchive.doc",OutputStream);4 }

CreateazipdynamicallywithinanASP.NETpostbackmethod,thendownloadthatzipfiletotherequestingbrowserthroughResponse.OutputStream.ThisworksinDotNetZipv1.5andlater.

ASP.NET11 publicvoidbtnGo_Click(Objectsender,EventArgse)2 {3 Response.Clear();4 StringReadmeText="Thisisazipfiledynamicallygeneratedat"5 stringfilename=System.IO.Path.GetFileName(ListOfFiles.SelectedItem.Text)+6 Response.ContentType="application/zip";7 Response.AddHeader("content-disposition","filename="89 using(ZipFilezip=newZipFile())10 {11 zip.AddFile(ListOfFiles.SelectedItem.Text,"files"12 zip.AddStringAsFile(ReadmeText,"Readme.txt",""13 zip.Save(Response.OutputStream);14 }1516 Response.End();17 }

Copy

Copy

Createazipwithasingleentry,obtainingthecontentforthatentryfromastring.Attachacommenttothatentry.Specifythenameofthezipfileatthetimeofsave.

ContentfromString1 stringcontent="......whatever....";2 using(ZipFilezip=newZipFile())3 {4 ZipEntrye=zip.AddEntry("README.txt",content);5 e.Comment="Thisentryintheziparchivewascreatedfromastring."6 zip.Save("archive-2008july12.zip");7 }

Openanexistingziparchiveandmodifyit:updateoneentry,removeanother,andrenameathird.Updatethecommentonthearchiveaswell.

UpdateaZip1 using(ZipFilezip=ZipFile.Read("ExistingArchive.zip"2 {3 ZipEntrye=zip["README.txt"];4 e.RemoveEntry();56 //forthisentry,updatethearchivewithcontentfromthefilesystem7 zip.UpdateItem("Portfolio.doc");89 //updatethefilenameofanentry10 e=zip["Table1.jpg"];11 e.FileName="Figure1.jpg";1213 zip.Comment="Thisziparchivewasupdated"+System.DateTime.ToString(14 zip.Save();15 }

Copy

Copy

DotNetZip-VB.NETExamplesHereareabunchofexamplesinVB.NETshowinghowtousethelibrary.

Therearealsoafewcomplete,workingexampleapplicationsshippedinthesourcecodedistribution.

Additemstoazipfile:

CreateaZip1 Try2 UsingzipAsZipFile=NewZipFile3 zip.AddFile("c:\photos\personal\7440-N49th.png"4 zip.AddFile("c:\Desktop\2005_Annual_Report.pdf"5 zip.AddFile("ReadMe.txt")6 zip.Save("MyZipFile.zip")7 EndUsing8 Catchex1AsException9 Console.Error.WriteLine("exception:{0}",ex1.ToString)10 EndTry

Extractitemsfromazipfile:

ExtractentriesfromaZip1 Try2 UsingzipAsZipFile=ZipFile.Read(ZipFileToExtract)3 DimeAsZipEntry4 ForEacheInzip5 e.Extract6 Next

Copy

Copy

7 EndUsing8 Catchex1AsException9 Console.Error.WriteLine("exception:{0}",ex1.ToString)10 EndTry

Extractallentries,andsettheStatusMessageTextWritersothatverbosemessagesaregenerated:

ExtractAll,andusethestatusTextWriter1 UsingzipAsZipFile=ZipFile.Read(FilePath)2 zip.StatusMessageTextWriter=System.Console.Out3 'StatusMessageswillbesenttotheconsoleduringextraction4 zip.ExtractAll()5 EndUsing

Addafewfilestoazipfile,specifyingdifferentpasswordsfordifferentitems:

CreateaZip,entriesgetpasswords1 Try2 UsingzipAsNewZipFile3 'thefirstentryisnotprotectedbyapassword4 zip.AddFile("c:\datafiles\ReadMe.txt","")5 zip.Password="123456!"6 zip.AddFile("c:\photos\personal\7440-N49th.png"7 zip.Password="!Secret1";8 zip.AddFile("c:\Desktop\2005_Annual_Report.pdf"9 zip.Save("Secret.zip")10 EndUsing11 Catchex1AsSystem.Exception12 System.Console.Error.WriteLine("exception:{0}",ex1)13 EndTry

Copy

Copy

Addafewfilestoazipfile,usingWinZip-compatibleAESencryptionontheentries:

CreateaZip,usingAESencryptionfortheentries1 Try2 UsingzipAsNewZipFile3 zip.Password="The.Silvertones.Box.Set!"4 zip.Encryption=EncryptionAlgorithm.WinZipAes2565 zip.AddFile("c:\datafiles\RawData-2008-12-20.csv"6 zip.AddFile("c:\photos\personal\7440-N49th.png"7 zip.AddFile("c:\Desktop\2005_Annual_Report.pdf"8 zip.Save("AES-Encrypted-Secret.zip")9 EndUsing10 Catchex1AsSystem.Exception11 System.Console.Error.WriteLine("exception:{0}",ex1)12 EndTry

Extractentriesusingapassword:

Extractentriesusingapassword1 UsingzipAsnewZipFile(FilePath)2 DimeAsZipEntry3 ForEacheInzip4 If(e.UsesEncryption)5 e.ExtractWithPassword("Secret!")6 Else7 e.Extract8 EndIf9 Next10 EndUsing

ThisexamplecreatesazipusingZIP64extensions.ZIP64allowsyou

Copy

Copy

Copy

toexceed4gbinazip,or65535entriesinazip.

CreateaZipthatusesZIP64extensions1 Try2 UsingzipAsZipFile=NewZipFile3 zip.UseZip64WhenSaving=Zip64Option.AsNecessary4 zip.AddFile("c:\datafiles\RawData-2009-02-12.csv"5 zip.AddFile("ReadMe.txt")6 zip.Save(String.Format("backup-{0}.zip",DateTime.Now.ToString(7 EndUsing8 Catchex1AsException9 Console.Error.WriteLine("exception:{0}",ex1.ToString)10 EndTry

Createazipfile,addafile,andalsoaddanentryfromastring.Whenthezipisunzipped,thecontentfromthestringwillbeinsertedintothefile"Readme.txt".

Create31 DimContentAsString="ThisstringwillbethecontentoftheReadme.txtfileintheziparchive."2 Usingzip1AsZipFile=NewZipFile3 zip1.AddEntry("Readme.txt","Thisisthereadmecontent..."4 zip1.AddFile("MyDocuments\Resume.doc","files")5 zip1.Comment=("Thiszipfilewascreatedat"&DateTime.Now.ToString(6 zip1.Save("Content.zip")7 EndUsing

Createazipfile,andaddanentrytakingcontentfromastream,likeaMemoryStreamoraFileStream.

Create41 DimContentAsString="ThisstringwillbethecontentoftheReadme.txtfileintheziparchive."

Copy

2 Usingzip1AsZipFile=NewZipFile3 zip1.AddEntry("Readme.txt",stream)4 zip1.AddFile("MyDocuments\Resume.doc","files")5 zip1.Comment=("Thiszipfilewascreatedat"&DateTime.Now.ToString(6 zip1.Save("Content.zip")7 EndUsing

Readinazipfile,removeafewentries,savethefile:

ModifyaZip1 DimswAsNewSystem.IO.StringWriter2 UsingzipAsZipFile=ZipFile.Read("PackedDocuments.zip"3 DimThresholdAsNewDateTime(2007,7,4)4 'Wecannotremovetheentryfromthelist,withinthecontextof5 'anenumerationofsaidlist.6 'Soweaddthedoomedentrytoalisttoberemovedlater.7 'pass1:marktheentriesforremoval8 DimMarkedEntriesAsNewSystem.Collections.Generic.List(9 DimeAsZipEntry10 ForEacheInzip11 If(e.LastModifiedName=$zipOutput;5 $dirToZip="c:\\temp\\psh";6 $zip->Encryption=3;7 $zip->Password="AES-Encryption-Is-Secure";8 $zip->AddDirectory($dirToZip);9 $zip->Save();10 $zip->Dispose();1112 if(file_exists($zipOutput))13 {14 header('Cache-Control:no-cache,must-revalidate');15 header('Content-Type:application/x-zip');16 header('Content-Disposition:attachment;filename='.$fname);17 header('Content-Length:'.filesize($zipOutput));18 readfile($zipOutput);19 unlink($zipOutput);20 }

Copy

UsingDotNetZipinJavascript

Thisexampledynamicallycreatesazipfile,usingAES256-bitencryption.

CreateaZip1 varfilename="C:\\temp\\ZipFile-created-from-javascript-"23 try4 {5 WScript.echo("InstantiatingaZipFileobject..."6 varzip=newActiveXObject("Ionic.Zip.ZipFile"78 WScript.echo("settingtheencryption...");9 //3=AES256,2=AES128,1=PKZIP,0=none10 zip.Encryption=3;1112 WScript.echo("settingthepassword...");13 zip.Password="ThisisthePassword.";1415 WScript.echo("addingaselectionoffiles...");16 zip.AddSelectedFiles("*.js");17 zip.AddSelectedFiles("*.vbs");1819 WScript.echo("settingthesavename...");20 zip.Name=filename;2122 WScript.echo("Saving...");23 zip.Save();2425 WScript.echo("Disposing...");26 zip.Dispose();2728 WScript.echo("Done.");

Copy

29 }30 catch(e2)31 {32 WScript.echo(e2.number+":"+e2.name);33 WScript.echo(e2.message);34 }

Thisexampleliststheentriesinazipfile.

ListingentriesinaZiparchive1 varfilename="C:\\temp\\CompressedData.zip";23 try4 {5 WScript.echo("InstantiatingaZipFileobject..."6 varzip=newActiveXObject("Ionic.Zip.ZipFile"78 WScript.echo("Initialize(Read)...("+filename+9 zip.Initialize(filename);1011 WScript.echo("listingentries...");12 vare=newEnumerator(zip);13 for(;!e.atEnd();e.moveNext())14 {15 varentry=e.item();16 WScript.Echo(""+entry.FileName);17 }1819 WScript.echo("Disposing...")20 zip.Dispose();2122 WScript.echo("Done.");23 }24 catch(e2)25 {26 WScript.echo(e2.number+":"+e2.name);

Copy

27 WScript.echo(e2.message);28 }

ThisexamplechecksaZipFileusingtheComHelperclass.

CheckingafiletoseeifitisaZiparchive1 functioncheckZip(filename)2 {3 varobj=newActiveXObject("Ionic.Zip.ComHelper"4 returnobj.IsZipFile(filename);5 }67 functioncheckZipWithExtract(filename)8 {9 varobj=newActiveXObject("Ionic.Zip.ComHelper"10 returnobj.IsZipFileWithExtract(filename);11 }1213 functionmain()14 {15 varresult;16 varargs=WScript.Arguments;1718 if(args.Length==1)19 {20 result=checkZip(args(0));21 }22 elseif(args.Length==2&&args(0)=="-x")23 {24 result=checkZipWithExtract(args(1));25 }26 else27 {28 WScript.Echo("TestCheckZip.js-checkazipfileusingJavascript."29 WScript.Echo("usage:TestCheckZip.js[-x]"30 WScript.Quit(1);

31 }3233 WScript.Echo((result==0)?"ThatzipisnotOK":"ThatzipisOK"34 WScript.Quit(0);35 }3637 main();

Copy

UsingDotNetZipinVBScript

Thisexamplecreatesazipfile,usingAES256-bitencryption.

CreateaZip1 dimfilename2 filename="C:\temp\ZipFile-created-from-VBScript.zip"34 WScript.echo("InstantiatingaZipFileobject...")5 dimzip6 setzip=CreateObject("Ionic.Zip.ZipFile")78 WScript.echo("Settingtheencryption...")9 '3=AES256,2=AES128,1=PKZIP,0=none10 zip.Encryption=31112 WScript.echo("settingthepassword...")13 zip.Password="ThisisthePassword."1415 WScript.echo("addingaselectionoffiles...")16 zip.AddSelectedFiles"*.js"17 zip.AddSelectedFiles"*.vbs"1819 WScript.echo("settingthesavename...")20 zip.Name=filename2122 WScript.echo("Saving...")23 zip.Save2425 WScript.echo("Disposing...")26 zip.Dispose2728 zip=Nothing29

Copy

Copy

30 WScript.echo("Done.")

Thisexampleextractsallentriesfromazipfile.

ExtractallentriesfromaZip1 WScript.echo("InstantiatingaZipFileobject...")2 dimzip3 setzip=CreateObject("Ionic.Zip.ZipFile")45 WScript.echo("Initialize(Read)...")6 zip.Initialize("CompressedData.zip")78 WScript.echo("settingthepasswordforextraction..."9 zip.Password="ThisisthePassword."1011 WScript.echo("extractingallfiles...")12 zip.ExtractAll"DotNetZip-extract"1314 WScript.echo("Disposing...")15 zip.Dispose1617 WScript.echo("Done.")

Thisexampleliststheentriesinazipfile,andextractssomeofthem.

ListandMaybeextractentriesfromaZip1 WScript.echo("")2 Dimzip3 WScript.echo("InstantiatingaZipFileobject...")4 Setzip=CreateObject("Ionic.Zip.ZipFile")56 WScript.echo("Initialize(Read)...")7 zip.Initializefilename89 Setfso=CreateObject("Scripting.FileSystemObject"

Copy

10 IfNotfso.FolderExists("unpack")Then11 fso.CreateFolder("unpack")12 EndIf1314 'AnycalltoZipEntry.Extract()willputfilesintothe15 'currentworkingdirectory.Sosetithere:16 SetobjShell=CreateObject("Wscript.Shell")17 objShell.CurrentDirectory="unpack"1819 WScript.echo("listing...")20 ForEachentryinzip21 WScript.echo(""&entry.FileName)22 ext=Right(entry.FileName,4)23 If(ext=".vbs")Then24 'setpasswordforextractionifnecessary25 entry.Password="ThisisthePassword."26 entry.Extract27 EndIf28 Next2930 WScript.echo("Disposing...")31 zip.Dispose3233 WScript.echo("Done.")

Thisexampleextractsselectedentriesfromaziparchive,viatheExtractSelectedEntriesoverload.Itusesthemanglednametoaccessthemethod,asdescribedabove.

ExtractselectedentriesfromaZip1 SubextractZip()2 IfNot(extractLocation="")Then3 DimOverwriteSilently4 OverwriteSilently=156 Dimzip

7 Setzip=CreateObject("Ionic.Zip.ZipFile")89 zip.Initializefilename1011 Ifpassword""Then12 zip.Password=password13 EndIf1415 zip.ExtractSelectedEntries_5"name=*.xml",1617 zip.Dispose18 zip=Nothing19 EndIf2021 EndSub

Copy

YoucanuseDotNetZipfromC++/CLIAprogramwritteninC++/CLIcantakeadvantageofanymanagedlibrary.It"seasytouseDotNetZipfromaC++/CLIapplication.Thispagewillshowsomeexamples.

UsingC++/CLI,thekeydifferencefromVBandC#,isthatthereisnousingstatementinC++.C++applicationsneedtosurroundtheuseoftheZipFileclasswithatry..catch..andcalltheZipFiledestructor,orcalldelete,inthefinallyclause.

Createazipfile

Thisexamplejustcreatesasimplezipfile.Itusesthedestructor.

CreateaZiparchive-destructor1 usingnamespaceSystem;2 usingnamespaceIonic::Zip;34 intmain(array^args)5 {6 Console::WriteLine(L"HelloWorld");78 ZipFile^zip;9 try10 {11 zip=gcnewZipFile();12 zip->AddEntry("Readme.txt","ThisisthecontentfortheReadme.txtentry."13 zip-&gtAddFile("CreateZipFile.cpp");14 zip->Save("test.zip");15 }

Copy

16 finally17 {18 zip->~ZipFile();19 }2021 Console::WriteLine(L"Presstoquit.");22 Console::ReadLine();23 return0;24 }

ThisalternativeusestheC++deleeesyntax:

CreateaZiparchive-delete1 usingnamespaceSystem;2 usingnamespaceIonic::Zip;34 intmain(array^args)5 {6 Console::WriteLine(L"HelloWorld");78 ZipFile^zip;9 try10 {11 zip=gcnewZipFile();12 zip->AddEntry("Readme.txt","ThisisthecontentfortheReadme.txtentry."13 zip-&gtAddFile("CreateZipFile.cpp");14 zip->Save("test.zip");15 }16 finally17 {18 deletezip;19 }2021 Console::WriteLine(L"Presstoquit.");22 Console::ReadLine();23 return0;

24 }

BuildingC++/CLIprogramthatusesDotNetZip

BuildaC++/CLIprogramthatusesDotNetZip,justasyouwouldbuildanyC++/CLIprogram.

TheeasiestwayistouseVisualStudio,andcreateaC++/CLIproject.RightclickontheprojectandselectReferences....AddareferencetotheIonic.Zip.dllassembly.ClickOK,thenbuildyourapplication.

Youcanalsobuildusingcommand-linetools.Todothis,youwillneedtocompileusingthec++sourceusingthecl.exetool,specifyingthe/clroption,andspecifyingwheretofindtheIonic.Zip.dllassembly.AtypicalseriesofstepstobuildasimpleC++/CLIprogramthatusesDotNetZipfromonesourcefile,supposingthenameofthesourcefileisCreateZipFile.cpp,is:

\vc9\bin\cl.exe/Od/FD/EHa/MDd/Fo".\\"-I\vc9\include/W3/c/Zi/clr/TP/FU"c:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll"/FUIonic.Zip.dllCreateZipFile.cpp

\vc9\bin\link.exe/OUT:CreateZipFile.exe/DEBUG/ASSEMBLYDEBUG/MANIFEST/MANIFESTFILE:"CreateZipFile.exe.intermediate.manifest"/MANIFESTUAC:"level='asInvoker'uiAccess='false'"/PDB:CreateZipFile.pdb/DYNAMICBASE/FIXED:No/NXCOMPAT/MACHINE:X86/LIBPATH:\vc9\lib/LIBPATH:\winsdk\libCreateZipFile.obj

c:\netsdk2.0\Bin\mt.exe/outputresource:"CreateZipFile.exe;#1"/manifestCreateZipFile.exe.intermediate.manifest

CreateazipfileusingAESencryption

Copy

Thisexamplecreatesazipfile,usingAES128-bitencryptiontoencrypttheentries.

Createanencryptedzip1 #include"stdafx.h"23 usingnamespaceSystem;4 usingnamespaceIonic::Zip;56 intmain(array^args)7 {8 Console::WriteLine(L"HelloWorld");910 ZipFile^zip;11 try12 {13 zip=gcnewZipFile();14 zip->Password=verySecret;15 zip->Encryption=EncryptionAlgorithm::WinZipAes128;16 zip->AddEntry("Readme.txt","ThisisthecontentfortheReadme.txtentry."17 zip->AddFile("Data.csv");18 zip->Save("test.zip");19 }20 finally21 {22 zip->~ZipFile();23 }2425 Console::WriteLine(L"Presstoquit.");26 Console::ReadLine();27 return0;28 }

UseaSaveProgresseventfromC++

Copy

Thisexamplecreatesazipfile,andusesaSaveProgressevent.

Createanencryptedzip1 #include"stdafx.h"23 usingnamespaceSystem;4 usingnamespaceSystem::IO;5 usingnamespaceIonic::Zip;678 publicrefclassDnzHelloCppCli9 {1011 private:12 booljustHadByteUpdate;1314 public:15 DnzHelloCppCli()16 {17 }1819 public:20 voidRun()21 {22 Console::WriteLine(L"HelloWorld");23 Console::WriteLine("UsingDotNetZipversion{0}"24 array^filesToAdd=System::IO::Directory::GetFiles(2526 ZipFile^zip;27 try28 {29 zip=gcnewZipFile();30 zip->Password="Harbinger";31 zip->Encryption=EncryptionAlgorithm::WinZipAes128;32 zip->SaveProgress+=gcnewEventHandler(33 zip->AddEntry("Readme.txt","ThisisthecontentfortheReadme.txtentry."

34 zip->AddFiles(filesToAdd,"files");35 zip->Save("MyArchive.zip");36 }37 finally38 {39 zip->~ZipFile();40 }4142 Console::WriteLine(L"Presstoquit."43 Console::ReadLine();44 return;45 }4647 public:48 voidSaveProgress(Object^sender,SaveProgressEventArgs^e)49 {50 switch(e->EventType)51 {52 caseZipProgressEventType::Saving_Started:53 {54 Console::WriteLine("Saving:{0}"55 break;56 }57 caseZipProgressEventType::Saving_BeforeWriteEntry:58 {59 if(this->justHadByteUpdate)60 {61 Console::WriteLine();62 }63 Console::WriteLine("Writing:{0}({1}/{2})"64 e->CurrentEntry->FileName,65 (e->EntriesSaved+66 e->EntriesTotal);67 this->justHadByteUpdate=false68 break;69 }70 caseZipProgressEventType::Saving_AfterWriteEntry:

71 {72 if(e->CurrentEntry->InputStreamWasJitProvided)73 {74 e->CurrentEntry->InputStream->Close();75 e->CurrentEntry->InputStream=76 }77 break;78 }79 caseZipProgressEventType::Saving_Completed:80 {81 this->justHadByteUpdate=false82 Console::WriteLine();83 Console::WriteLine("Done:{0}",e->ArchiveName);84 break;85 }86 caseZipProgressEventType::Saving_EntryBytesRead:87 {88 if(this->justHadByteUpdate)89 {90 Console::SetCursorPosition(91 }92 Console::Write("{0}/{1}({2:N0}%)"93 e->BytesTransferred,94 e->TotalBytesToTransfer,95 (((double)e->BytesTransferred)/(96 this->justHadByteUpdate=true;97 break;98 }99 }100 }101102 };103104105 intmain(array^args)106 {107 try

108 {109 DnzHelloCppCli^me=gcnewDnzHelloCppCli();110 me->Run();111 }112 catch(Exception^ex1)113 {114 Console::Error->WriteLine(String::Concat("exception:"115 }116 return0;117 }

CompressionCommand-LineToolsTheTools/UtilitiesdownloadsforDotNetZipincludesapairofcommand-linetoolsthatperformrawcompressionanddecompression:GZip.exeandBZip2.exe.Thesetoolscanbeusedfromthecommandlinetocompressordecompress.gzand.bz2files,respectively,fromwithinbatchscripts,orCMD.exewindows.

GZip.exe

Thistoolcanbeusedtocompressaregularfileintoa.gzfile,ortodecompressa.gzfilesintoitsoriginal,uncompressedform.Ithandlesfilesinthe.gzformatcreatedbyotherGZIPtools,suchasthegziptoolthatisincludedwithLinuxandotheroperatingsystems,andthe.gzfilesitproducesonWindowscanbereadbythegziptoolonotherplatforms.

Ofinterest,theGZipformathandledbythistoolisspecifiedinIETFRFC1952.WhiletheGZIPformatcanhandlemultipleentrieswithinasinglearchive,ingeneralthatfeatureisrarelyused.Instead,mostusesofGZipcompressasinglefiletoasingle.gzfile.

Usage

GZip.exe[arguments]

arguments:-v-verboseoutput.-f-forceoverwriteofanyexistingfiles.-keep-don'tdeletetheoriginalfileaftercompressingordecompressingit.

http://www.gzip.org/zlib/rfc-gzip.html

BZip2.exe

Thistoolcanbeusedtocreate.bz2files,thatconformtotheBZIP2format.Bzip2wascreatedin1996asacompressionmethodandformatthatcanbeappliedtosinglefiles.UnlikeZIP,itisnotamulti-entryarchiveformat-youusebzip2tocompressasinglefileintoasinglecompressedimage.Byconvention,foragivenfilename,abzip2compressorcreatesanewfilecalledfilename.bz2.

UsingtheBZip2.execommandlinetoolincludedwithDotNetZip,youcancompressregularfilesinto.bz2files,andyoucandecompress.bz2filesintothecorrespondingoriginalfile.

Thistoolsuchiscompatiblewithotherbzip2tools,suchastheonethatisincludedwithLinuxandotheroperatingsystems.The.bz2filesthatthistoolproducesonWindowscanbereadbythebzip2toolonotherplatforms.

MostBzip2utilitiesdeletetheoriginalfileafterproducingthecompressedversion,anddeletethecompressedversionafterdecompressing.Thisutilityfollowsthatconvention.

BZip2isacompressionformat,similartoZLIB,GZIP,orDEFLATE.BZIP2tendstocompressbetterthantheseotheralgorithms,butBZIP2compressorstendtorequiremoretimetocompress.

Usage

BZip2.exe[arguments]

arguments:

-v-verboseoutput.-f-forceoverwriteofanyexistingfiles.-keep-don'tdeletetheoriginalfileaftercompressingordecompressingit.

CommandExamples

UsethisCommand... todothis...

gzip.exeLargeFile.txt compresstheLargeFile.txttoproduceLargeFile.txt.gz.gzip.exeLargeFile.txt.gz

decompresstheLargeFile.txt.gztoproduceLargeFile.txt,anddeleteLargeFile.txt.gz.gzip.exeLargeFile.txt.gz-keep

decompresstheLargeFile.txt.gztoproduceLargeFile.txt;theoriginalLargeFile.txt.gzwillnotbedeleted.bzip2.exeLargeFile.txt

compresstheLargeFile.txttoproduceLargeFile.txt.bz2,anddeletetheLargeFile.txtwhenfinished.bzip2.exeLargeFile.txt-keep

compresstheLargeFile.txttoproduceLargeFile.txt.bz2,andkeeptheLargeFile.txtwhenfinished.bzip2.exeLargeFile.txt.bz2

decompresstheLargeFile.txt.bz2toproduceLargeFile.txt,anddeletetheoriginalcompressedfilewhenfinished.

DotNetZipCommand-LineToolsTheTools/UtilitiesdownloadsforDotNetZipincludeapairoftools-Zipit.exeandUnzip.exe-thatcanbeusedfromthecommandlinetomanipulatezipfilesfromwithinbatchscripts,orCMD.exewindows.

ZipIt.exe

ThistoolcanbeusedtocreateZIPfiles,orupdateexistingZIPfiles,fromthecommandlineorfromabatchfile.

Usingthecommandlinetools,youcandovirtuallyeverythingyoucandobyusingthelibrarydirectlyfromacustomapplication.Youcancreateself-extractingarchivesorarchivesthatuseZIP64extensions.Youcancreatearchivesthatuseencryptionorpasswords.Youcancreatesplitorspannedarchives.Andtherearemanyotheroptions.

Usage

ZipIt.exe[arguments]

arguments:|-adirectoryorfiletoaddtothearchive.-afileselectionexpression.Examples:*.txt(name=*.txt)OR(name=*.xml)(attrs=H)OR(name!=*.xml)(ctime1g)AND(mtime2009-04-29)AND(size,>=,

SpecifyvaluesforthefileattributesasastringwithoneormoreofthecharactersH,R,S,A,I,Linanyorder,implyingfileattributesofHidden,ReadOnly,System,Archive,NotContextIndexed,andReparsePoint(symboliclink)respectively.

Tospecifyatime,useYYYY-MM-DD-HH:mm:ssorYYYY/MM/DD-HH:mm:ssastheformat.IfyouomittheHH:mm:ssportion,itisassumedtobe00:00:00(midnight).

Thevalueforasizecriterionisexpressedinintegerquantitiesofbytes,kilobytes(usekorkbafterthenumber),megabytes(mormb),orgigabytes(gorgb).

Thevalueforanameisapatterntomatchagainstthefilename,potentiallyincludingwildcards.ThepatternfollowsCMD.exeglobrules:*impliesoneormoreofanycharacter,while?impliesonecharacter.Ifthenamepatterncontainsanyslashes,itismatchedtotheentirefilename,includingthepath;otherwise,itismatchedagainstonlythefilenamewithoutthepath.Thismeansapatternof"*\*.*"matchesallfilesonedirectoryleveldeep,whileapatternof"*.*"matchesallfilesinalldirectories.

Tospecifyanamepatternthatincludesspaces,usesinglequotesaroundthepattern.Apatternof"'**.*'"willmatchallfilesthathavespacesinthefilename.Thefullcriteriastringforthatwouldbe"name='**.*'".

ThevalueforatypecriterioniseitherF(implyingafile)orD(implyingadirectory).

Someexamples:

criteria Filesretrievedname!=*.xls anyfilewithanextensionthatisnot.xls

name=*.mp3 anyfilewitha.mp3extension.

*.mp3 (sameasabove)anyfilewitha.mp3extension.

attributes=A allfileswhoseattributesincludetheArchivebit.

attributes!=H allfileswhoseattributesdonotincludetheHidden

bit.

mtime>2009-01-01

allfileswithalastmodifiedtimeafterJanuary1st,2009.

ctime>2009/01/01-03:00:00

allfileswithacreatedtimeafter3am(localtime),onJanuary1st,2009.

size>2gb allfileswhoseuncompressedsizeisgreaterthan2gb.

type=D alldirectoriesinthefilesystem.

YoucancombinecriteriawiththeconjunctionsAND,OR,andXOR.Usingastringlike"name=*.txtANDsize>=100k"fortheselectionCriteriaretrievesentrieswhosenamesendin.txt,andwhoseuncompressedsizeisgreaterthanorequalto100kilobytes.

Formorecomplexcombinationsofcriteria,youcanuseparenthesistogroupclausesinthebooleanlogic.Absentparenthesis,theprecedenceofthecriterionatomsisdeterminedbyorderofappearance.UnliketheC#language,theANDconjunctiondoesnottakeprecendenceoverthelogicalOR.Thisisimportantonlyinstringsthatcontain3ormorecriterionatoms.Inotherwords,"name=*.txtandsize>1000orattributes=H"implies"((name=*.txtANDsize>1000)ORattributes=H)"while"attributes=HORname=*.txtandsize>1000"evaluatesto"((attributes=HORname=*.txt)ANDsize>1000)".Whenindoubt,useparenthesis.

Usingtimepropertiesrequiressomeextracare.Ifyouwanttoretrieveallentriesthatwerelastupdatedon2009February14,specify"mtime>=2009-02-14ANDmtime,>=,

Someexamples:

criteria Filesretrievedname!=*.xls anyfilewithanextensionthatisnot.xls

name=*.mp3 anyfilewitha.mp3extension.

*.mp3 (sameasabove)anyfilewitha.mp3extension.

attributes=A allfileswhoseattributesincludetheArchivebit.

attributes!=H allfileswhoseattributesdonotincludetheHiddenbit.

mtime>2009-01-01

allfileswithalastmodifiedtimeafterJanuary1st,2009.

size>2gb allfileswhoseuncompressedsizeisgreaterthan2gb.

type=D alldirectoriesinthefilesystem.

YoucancombinecriteriawiththeconjunctionsANDorOR.Usingastringlike"name=*.txtANDsize>=100k"fortheselectionCriteriaretrievesentrieswhosenamesendin.txt,andwhoseuncompressedsizeisgreaterthanorequalto100kilobytes.

Formorecomplexcombinationsofcriteria,youcanuseparenthesistogroupclausesinthebooleanlogic.Withoutparenthesis,theprecedenceofthecriterionatomsisdeterminedbyorderofappearance.UnliketheC#language,theANDconjunctiondoesnottakeprecendenceoverthelogicalOR.Thisisimportantonlyinstringsthatcontain3ormorecriterionatoms.Inotherwords,"name=*.txtandsize>1000orattributes=H"implies"((name=*.txtANDsize>1000)ORattributes=H)"while"attributes=HORname=*.txtandsize>1000"evaluatesto"((attributes=HORname=*.txt)ANDsize>1000)".Whenindoubt,useparenthesis.

Usingtimepropertiesrequiressomeextracare.Ifyouwanttoretrieveallentriesthatwerelastupdatedon2009February14,specifyatimerangelikeso:"mtime>=2009-02-14ANDmtime1024kb"zip.Save(PathToZipArchive);}

VB.NET

UsingzipAsZipFile=NewZipFile()'UseacompoundexpressionintheselectionCriteriastring.zip.AddSelectedFiles("name=*.xmlandsize>1024kb"zip.Save(PathToZipArchive)EndUsing

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileAddSelectedFiles(String,String)C#

IonicZipLibraryv1.9.1.6AddSelectedFilesMethod(selectionCriteria,directoryOnDisk)

AddstotheZipFileasetoffilesfromaspecifieddirectoryinthefilesystem,thatconformtothespecifiedcriteria.

DeclarationSyntaxC# VisualBasic VisualC++

publicvoidAddSelectedFiles( stringselectionCriteria, stringdirectoryOnDisk)

PublicSubAddSelectedFiles(_ selectionCriteriaAsString,_ directoryOnDiskAsString_)

public:voidAddSelectedFiles( String^selectionCriteria, String^directoryOnDisk)

ParametersselectionCriteria(String)

Thecriteriaforfileselection

directoryOnDisk(String)Thenameofthedirectoryonthediskfromwhichtoselectfiles.

Remarks

Thismethodselectsfilesthatconformtothespecifiedcriteria,fromthe

http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

Copy

Copy

thespecifieddirectoryondisk,andaddsthemtotheZipFile.Thesearchdoesnotrecurseintosubdirectores.

Usingthismethod,thefullfilesystempathofthefilesondiskisreproducedontheentriesaddedtothezipfile.Ifyoudon'twantthisbehavior,useoneoftheotheroverloadsofthismethod.

FordetailsonthesyntaxfortheselectionCriteriaparameter,seeAddSelectedFiles(String).

ExamplesThisexamplezipsupall*.xmlfileslargerthan1mbinthedirectorygivenby"d:\rawdata".

C#

using(ZipFilezip=newZipFile()){//UseacompoundexpressionintheselectionCriteriastring.zip.AddSelectedFiles("name=*.xmlandsize>1024kb"zip.Save(PathToZipArchive);}

VB.NET

UsingzipAsZipFile=NewZipFile()'UseacompoundexpressionintheselectionCriteriastring.zip.AddSelectedFiles("name=*.xmlandsize>1024kb"zip.Save(PathToZipArchive)EndUsing

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileAddSelectedFiles(String,String,Boolean)

C#

IonicZipLibraryv1.9.1.6AddSelectedFilesMethod(selectionCriteria,directoryOnDisk,recurseDirectories)

AddstotheZipFileasetoffilesfromthespecifieddirectoryondisk,thatconformtothespecifiedcriteria.

DeclarationSyntaxC# VisualBasic VisualC++

publicvoidAddSelectedFiles( stringselectionCriteria, stringdirectoryOnDisk, boolrecurseDirectories)

PublicSubAddSelectedFiles(_ selectionCriteriaAsString,_ directoryOnDiskAsString,_ recurseDirectoriesAsBoolean_)

public:voidAddSelectedFiles( String^selectionCriteria, String^directoryOnDisk, boolrecurseDirectories)

ParametersselectionCriteria(String)

Thecriteriaforfileselection

directoryOnDisk(String)

http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

Copy

Copy

Thefilesystempathfromwhichtoselectfiles.

recurseDirectories(Boolean)Iftrue,thefileselectionwillrecurseintosubdirectories.

Remarks

Thismethodselectsfilesfromthethespecifieddiskdirectorymatchingthespecifiedselectioncriteria,andaddsthemtotheZipFile.IfrecurseDirectoriesistrue,filesarealsoselectedfromsubdirectories.

Thefulldirectorystructureinthefilesystemisreproducedontheentriesaddedtotheziparchive.Ifyoudon'twantthisbehavior,useoneoftheoverloadsofthismethodthatallowsthespecificationofadirectoryInArchive.

FordetailsonthesyntaxfortheselectionCriteriaparameter,seeAddSelectedFiles(String).

ExamplesThisexamplezipsupall*.csvfilesinthe"files"directory,oranysubdirectory,thathavebeensavedsince2009February14th.

C#

using(ZipFilezip=newZipFile()){//UseacompoundexpressionintheselectionCriteriastring.zip.AddSelectedFiles("name=*.csvandmtime>2009-02-14"zip.Save(PathToZipArchive);}

VB.NET

UsingzipAsZipFile=NewZipFile()'UseacompoundexpressionintheselectionCriteriastring.zip.AddSelectedFiles("name=*.csvandmtime>2009-02-14"zip.Save(PathToZipArchive)EndUsing

http://msdn2.microsoft.com/en-us/library/a28wyd50

Copy

ExamplesThisexamplezipsupallfilesinthecurrentworkingdirectory,andallitschilddirectories,exceptthoseintheexcludethissubdirectory.

VB.NET

UsingZipAsZipFile=NewZipFile(zipfile)Zip.AddSelectedFfiles("name!='excludethis\*.*'",datapath,Zip.Save()EndUsing

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileAddSelectedFiles(String,String,String)

C#

IonicZipLibraryv1.9.1.6AddSelectedFilesMethod(selectionCriteria,directoryOnDisk,directoryPathInArchive)

AddstotheZipFileaselectionoffilesfromthespecifieddirectoryondisk,thatconformtothespecifiedcriteria,andusingaspecifiedrootpathforentriesaddedtotheziparchive.

DeclarationSyntaxC# VisualBasic VisualC++

publicvoidAddSelectedFiles( stringselectionCriteria, stringdirectoryOnDisk, stringdirectoryPathInArchive)

PublicSubAddSelectedFiles(_ selectionCriteriaAsString,_ directoryOnDiskAsString,_ directoryPathInArchiveAsString_)

public:voidAddSelectedFiles( String^selectionCriteria, String^directoryOnDisk, String^directoryPathInArchive)

ParametersselectionCriteria(String)

ThecriteriaforselectionoffilestoaddtotheZipFile.

http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

Copy

Copy

directoryOnDisk(String)Thepathtothedirectoryinthefilesystemfromwhichtoselectfiles.

directoryPathInArchive(String)SpecifiesadirectorypathtousetoinplaceofthedirectoryOnDisk.Thispathmay,ormaynot,correspondtoarealdirectoryinthecurrentfilesystem.Ifthefileswithintheziparelaterextracted,thisisthepathusedfortheextractedfile.Passingnull(nothinginVB)willusethepathonthefilename,ifany;inotherwordsitwouldusedirectoryOnDisk,plusanysubdirectory.Passingtheemptystring("")willinserttheitemattherootpathwithinthearchive.

Remarks

Thismethodselectsfilesfromthespecifieddiskdirectorymatchingthespecifiedselectioncriteria,andaddsthosefilestotheZipFile,usingthespecifieddirectorypathinthearchive.Thesearchdoesnotrecurseintosubdirectories.FordetailsonthesyntaxfortheselectionCriteriaparameter,seeAddSelectedFiles(String).

ExamplesThisexamplezipsupall*.psdfilesinthe"photos"directorythathavebeensavedsince2009February14th,andputsthemallinazipfile,usingthedirectorynameof"content"intheziparchiveitself.Whentheziparchiveisunzipped,thefoldercontainingthe.psdfileswillbenamed"content".

C#

using(ZipFilezip=newZipFile()){//UseacompoundexpressionintheselectionCriteriastring.zip.AddSelectedFiles("name=*.psdandmtime>2009-02-14"zip.Save(PathToZipArchive);}

VB.NET

http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

UsingzipAsZipFile=NewZipFilezip.AddSelectedFiles("name=*.psdandmtime>2009-02-14"zip.Save(PathToZipArchive)EndUsing

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileAddSelectedFiles(String,String,String,Boolean)

C#

IonicZipLibraryv1.9.1.6AddSelectedFilesMethod(selectionCriteria,directoryOnDisk,directoryPathInArchive,recurseDirectories)

AddstotheZipFileaselectionoffilesfromthespecifieddirectoryondisk,thatconformtothespecifiedcriteria,optionallyrecursingthroughsubdirectories,andusingaspecifiedrootpathforentriesaddedtotheziparchive.

DeclarationSyntaxC# VisualBasic VisualC++

publicvoidAddSelectedFiles( stringselectionCriteria, stringdirectoryOnDisk, stringdirectoryPathInArchive, boolrecurseDirectories)

PublicSubAddSelectedFiles(_ selectionCriteriaAsString,_ directoryOnDiskAsString,_ directoryPathInArchiveAsString,_ recurseDirectoriesAsBoolean_)

public:voidAddSelectedFiles( String^selectionCriteria, String^directoryOnDisk, String^directoryPathInArchive, boolrecurseDirectories)

http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50

Copy

ParametersselectionCriteria(String)

ThecriteriaforselectionoffilestoaddtotheZipFile.directoryOnDisk(String)

Thepathtothedirectoryinthefilesystemfromwhichtoselectfiles.

directoryPathInArchive(String)SpecifiesadirectorypathtousetoinplaceofthedirectoryOnDisk.Thispathmay,ormaynot,correspondtoarealdirectoryinthecurrentfilesystem.Ifthefileswithintheziparelaterextracted,thisisthepathusedfortheextractedfile.Passingnull(nothinginVB)willusethepathonthefilename,ifany;inotherwordsitwouldusedirectoryOnDisk,plusanysubdirectory.Passingtheemptystring("")willinserttheitemattherootpathwithinthearchive.

recurseDirectories(Boolean)Iftrue,themethodalsoscanssubdirectoriesforfilesmatchingthecriteria.

RemarksThismethodselectsfilesfromthespecifieddiskdirectorythatmatchthespecifiedselectioncriteria,andaddsthosefilestotheZipFile,usingthespecifieddirectorypathinthearchive.IfrecurseDirectoriesistrue,filesarealsoselectedfromsubdirectories,andthedirectorystructureinthefilesystemisreproducedintheziparchive,rootedatthedirectoryspecifiedbydirectoryOnDisk.FordetailsonthesyntaxfortheselectionCriteriaparameter,seeAddSelectedFiles(String).

ExamplesThisexamplezipsupallfilesthatareNOT*.pstfiles,inthecurrentworkingdirectoryandanysubdirectories.

C#

using(ZipFilezip=newZipFile()){zip.AddSelectedFiles("name!=*.pst",SourceDirectory,

http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50

Copy

zip.Save(PathToZipArchive);}

VB.NET

UsingzipAsZipFile=NewZipFilezip.AddSelectedFiles("name!=*.pst",SourceDirectory,zip.Save(PathToZipArchive)EndUsing

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileAlternateEncodingIonicZipLibraryv1.9.1.6AlternateEncodingProperty

ATextEncodingtousewhenencodingthefilenamesandcommentsforalltheZipEntryitems,duringaZipFile.Save()operation.

DeclarationSyntaxC# VisualBasic VisualC++

publicEncodingAlternateEncoding{get;set;}

PublicPropertyAlternateEncodingAsEncoding Get Set

public:propertyEncoding^AlternateEncoding{ Encoding^get(); voidset(Encoding^value);}

Remarks

WhethertheencodingspecifiedhereisusedduringthesavedependsonAlternateEncodingUsage.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/86hf4sb8http://msdn2.microsoft.com/en-us/library/86hf4sb8http://msdn2.microsoft.com/en-us/library/86hf4sb8http://msdn2.microsoft.com/en-us/library/86hf4sb8http://msdn2.microsoft.com/en-us/library/86hf4sb8mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileAlternateEncodingUsageC#

IonicZipLibraryv1.9.1.6AlternateEncodingUsageProperty

AflagthattellsifandwhenthisinstanceshouldapplyAlternateEncodingtoencodethefilenamesandcommentsassociatedtoofZipEntryobjectscontainedwithinthisinstance.

DeclarationSyntaxC# VisualBasic VisualC++

publicZipOptionAlternateEncodingUsage{get;set;}

PublicPropertyAlternateEncodingUsageAsZipOption Get Set

public:propertyZipOptionAlternateEncodingUsage{ ZipOptionget(); voidset(ZipOptionvalue);}

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileBufferSizeIonicZipLibraryv1.9.1.6BufferSizeProperty

SizeoftheIObufferusedwhilesaving.

DeclarationSyntaxC# VisualBasic VisualC++

publicintBufferSize{get;set;}

PublicPropertyBufferSizeAsInteger Get Set

public:propertyintBufferSize{ intget(); voidset(intvalue);}

Remarks

First,letmesaythatyoureallydon'tneedtobotherwiththis.Itisheretoallowforoptimizationsthatyouprobablywon'tmake!Itwillworkfineifyoudon'tsetorgetthispropertyatall.Ok?

Nowthatwehavethatoutoftheway,thefineprint:ThispropertyaffectsthesizeofthebufferthatisusedforI/Oforeachentrycontainedinthezipfile.Whenafileisreadintobecompressed,itusesabuffergivenbythesizehere.Whenyouupdateazipfile,thedataforunmodifiedentriesiscopiedfromthefirstzipfiletotheother,throughabuffergivenbythesizehere.

Changingthebuffersizeaffectsafewthings:first,forlargerbuffersizes,thememoryusedbytheZipFile,obviously,willbelargerduringI/Ooperations.Thismaymakeoperationsfasterforverymuchlargerfiles.Last,foranygivenentry,whenyouusealargerbuffertherewillbefewer

http://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409d

Copy

progresseventsduringI/Ooperations,becausethere'soneprogresseventgeneratedforeachtimethebufferisfilledandthenemptied.

Thedefaultbuffersizeis8k.Increasingthebuffersizemayspeedthingsupasyoucompresslargerfiles.Buttherearenohard-and-fastruleshere,eh?Youwon'tknowtilyoutestit.Andtherewillbealimitwhereeverlargerbuffersactuallyslowthingsdown.SoasIsaidinthebeginning,it'sprobablybestifyoudon'tsetorgetthispropertyatall.

ExamplesThisexampleshowshowyoumightsetalargebuffersizeforefficiencywhendealingwithzipentriesthatarelargerthan1gb.

C#

using(ZipFilezip=newZipFile()){zip.SaveProgress+=this.zip1_SaveProgress;zip.AddDirectory(directoryToZip,"");zip.UseZip64WhenSaving=Zip64Option.Always;zip.BufferSize=65536*8;//65536*8=512kzip.Save(ZipFileToCreate);}

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileBufferSizeDefaultIonicZipLibraryv1.9.1.6BufferSizeDefaultField

DefaultsizeofthebufferusedforIO.

DeclarationSyntaxC# VisualBasic VisualC++

publicstaticreadonlyintBufferSizeDefault

PublicSharedReadOnlyBufferSizeDefaultAsInteger

public:staticinitonlyintBufferSizeDefault

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dmailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileCaseSensitiveRetrievalC#

IonicZipLibraryv1.9.1.6CaseSensitiveRetrievalProperty

Indicateswhethertoperformcase-sensitivematchingonthefilenamewhenretrievingentriesinthezipfileviathestring-basedindexer.

DeclarationSyntaxC# VisualBasic VisualC++

publicboolCaseSensitiveRetrieval{get;set;}

PublicPropertyCaseSensitiveRetrievalAsBoolean Get Set

public:propertyboolCaseSensitiveRetrieval{ boolget(); voidset(boolvalue);}

RemarksThedefaultvalueisfalse,whichmeansdon'tdocase-sensitivematching.Inotherwords,retrievingzip["ReadMe.Txt"]isthesameaszip["readme.txt"].ItreallymakessensetosetthistotrueonlyifyouarenotrunningonWindows,whichhascase-insensitivefilenames.Butsincethislibraryisnotbuiltfornon-Windowsplatforms,inmostcasesyoushouldjustleavethispropertyalone.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileCheckZip()IonicZipLibraryv1.9.1.6CheckZipMethod

MembersIcon Member Description

CheckZip(String) Checksazipfiletoseeifitsdirectoryisconsistent.

CheckZip(String,Boolean,TextWriter)

Checksazipfiletoseeifitsdirectoryisconsistent,andoptionallyfixesthedirectoryifnecessary.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileCheckZip(String)IonicZipLibraryv1.9.1.6CheckZipMethod(zipFileName)

Checksazipfiletoseeifitsdirectoryisconsistent.

DeclarationSyntaxC# VisualBasic VisualC++

publicstaticboolCheckZip( stringzipFileName)

PublicSharedFunctionCheckZip(_ zipFileNameAsString_)AsBoolean

public:staticboolCheckZip( String^zipFileName)

ParameterszipFileName(String)

Thefilenametoofthezipfiletocheck.

ReturnValuetrueifthenamedzipfilechecksOK.Otherwise,false.

Remarks

Incasesofdataerror,thedirectorywithinazipfilecangetoutofsynchwiththeentriesinthezipfile.Thismethodchecksthegivenzipfileandreturnstrueifthishasoccurred.

Thismethodmaytakealongtimetorunforlargezipfiles.

http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

ThismethodisnotsupportedintheReducedorCompactFrameworkversionsofDotNetZip.

DevelopersusingCOMcanusetheComHelper.CheckZip(String)method.

SeeAlsoFixZipDirectory(String)CheckZip(String,Boolean,TextWriter)

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileCheckZip(String,Boolean,TextWriter)

C#

IonicZipLibraryv1.9.1.6CheckZipMethod(zipFileName,fixIfNecessary,writer)

Checksazipfiletoseeifitsdirectoryisconsistent,andoptionallyfixesthedirectoryifnecessary.

DeclarationSyntaxC# VisualBasic VisualC++

publicstaticboolCheckZip( stringzipFileName, boolfixIfNecessary, TextWriterwriter)

PublicSharedFunctionCheckZip(_ zipFileNameAsString,_ fixIfNecessaryAsBoolean,_ writerAsTextWriter_)AsBoolean

public:staticboolCheckZip( String^zipFileName, boolfixIfNecessary, TextWriter^writer)

ParameterszipFileName(String)

Thefilenametoofthezipfiletocheck.

fixIfNecessary(Boolean)Iftrue,themethodwillfixthezipfileifnecessary.

http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/ywxh2328http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/ywxh2328http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/ywxh2328http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50

writer(TextWriter)aTextWriterinwhichmessagesgeneratedwhilecheckingwillbewritten.

ReturnValuetrueifthenamedzipisOK;falseifthefileneedstobefixed.

Remarks

Incasesofdataerror,thedirectorywithinazipfilecangetoutofsynchwiththeentriesinthezipfile.Thismethodchecksthegivenzipfile,andreturnstrueifthishasoccurred.Italsooptionallyfixesthezipfile,savingthefixedcopyinName_Fixed.zip.

Thismethodmaytakealongtimetorunforlargezipfiles.Itwilltakeevenlongerifthefileactuallyneedstobefixed,andiffixIfNecessaryistrue.

ThismethodisnotsupportedintheReducedorCompactFrameworkversionsofDotNetZip.

SeeAlsoCheckZip(String)FixZipDirectory(String)

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/ywxh2328mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileCheckZipPassword(String,String)

C#

IonicZipLibraryv1.9.1.6CheckZipPasswordMethod(zipFileName,password)

Verifythepasswordonazipfile.

DeclarationSyntaxC# VisualBasic VisualC++

publicstaticboolCheckZipPassword( stringzipFileName, stringpassword)

PublicSharedFunctionCheckZipPassword(_ zipFileNameAsString,_ passwordAsString_)AsBoolean

public:staticboolCheckZipPassword( String^zipFileName, String^password)

ParameterszipFileName(String)

Thefilenametoofthezipfiletofix.

password(String)Thepasswordtocheck.

ReturnValueaboolindicatingwhetherthepasswordmatches.

http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbf

Remarks

Keepinmindthatpasswordsinzipfilesareappliedtozipentries,nottotheentirezipfile.Sotestingazipfileforaparticularpassworddoesn'tworkinthegeneralcase.Ontheotherhand,it'softenthecasethatasinglepasswordwillbeusedonallentriesinazipfile.Thismethodworksforthatcase.

Thereisnowaytocheckapasswordwithoutdoingthedecryption.SothiscodedecryptsandextractsthegivenzipfileintoNull

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/z5b68e43mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileCodecBufferSizeIonicZipLibraryv1.9.1.6CodecBufferSizeProperty

SizeoftheworkbuffertousefortheZLIBcodecduringcompression.

DeclarationSyntaxC# VisualBasic VisualC++

publicintCodecBufferSize{get;set;}

PublicPropertyCodecBufferSizeAsInteger Get Set

public:propertyintCodecBufferSize{ intget(); voidset(intvalue);}

Remarks

WhendoingZLIBorDeflatecompression,thelibraryfillsabuffer,thenpassesittothecompressorforcompression.Thenthelibraryreadsoutthecompressedbytes.Thishappensrepeatedlyuntilthereisnomoreuncompresseddatatocompress.Thispropertysetsthesizeofthebufferthatwillbeusedforchunk-wisecompression.Inorderforthesettingtotakeeffect,yourapplicationneedstosetthispropertybeforecallingoneoftheZipFile.Save()overloads.

Settingthisaffectstheperformanceandmemoryefficiencyofcompressionanddecompression.Forlargerfiles,settingthistoalargersizemayimprovecompressionperformance,buttheexactnumbersvarydependingonavailablememory,thesizeofthestreamsyouarecompressing,andabunchofothervariables.Idon'thavegoodfirmrecommendationsonhowtosetit.You'llhavetotestityourself.Orjustleaveitaloneandacceptthedefault.

http://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409d

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileCommentIonicZipLibraryv1.9.1.6CommentProperty

Acommentattachedtotheziparchive.

DeclarationSyntaxC# VisualBasic VisualC++

publicstringComment{get;set;}

PublicPropertyCommentAsString Get Set

public:propertyString^Comment{ String^get(); voidset(String^value);}

Remarks

Thispropertyisread/write.ItallowstheapplicationtospecifyacommentfortheZipFile,orreadthecommentfortheZipFile.Aftersettingthisproperty,changesareonlymadepermanentwhenyoucallaSave()method.

AccordingtoPKWARE'szipspecification,thecommentisnotencrypted,evenifthereisapasswordsetonthezipfile.

Thespecificationdoesnotdescribehowtoindicatetheencodingusedonacommentstring.Many"compliant"ziptoolsandlibrariesuseIBM437asthecodepageforcomments;DotNetZip,too,followsthatpractice.Ontheotherhand,therearesituationswhereyouwantaCommenttobeencodedwithsomethingelse,forexampleusingcodepage950"Big-5Chinese".Tofillthatneed,DotNetZipwillencodethecommentfollowingthesameprocedureitfollowsforencodingfilenames:(a)if

http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://www.pkware.com/documents/casestudies/APPNOTE.TXT

AlternateEncodingUsageisNever,itusesthedefaultencoding(IBM437).(b)ifAlternateEncodingUsageisAlways,italwaysusesthealternateencoding(AlternateEncoding).(c)ifAlternateEncodingUsageisAsNecessary,itusesthealternateencodingonlyifthedefaultencodingisnotsufficientforencodingthecomment-inotherwordsifdecodingtheresultdoesnotproducetheoriginalstring.ThisdecisionistakenatthetimeofthecalltoZipFile.Save().

Whencreatingaziparchiveusingthislibrary,itispossibletochangethevalueofAlternateEncodingbetweeneachentryyouadd,andbetweenaddingentriesandthecalltoSave().Don'tdothis.Itwilllikelyresultinazipfilethatisnotreadablebyanytoolorapplication.Forbestinteroperability,leaveAlternateEncodingalone,orspecifyitonlyonce,beforeaddinganyentriestotheZipFileinstance.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileCompressionLevelIonicZipLibraryv1.9.1.6CompressionLevelProperty

Setsthecompressionleveltobeusedforentriessubsequentlyaddedtotheziparchive.

DeclarationSyntaxC# VisualBasic VisualC++

publicCompressionLevelCompressionLevel{get;set;}

PublicPropertyCompressionLevelAsCompressionLevel Get Set

public:propertyCompressionLevelCompressionLevel{ CompressionLevelget(); voidset(CompressionLevelvalue);}

Remarks

Varyingthecompressionlevelusedonentriescanaffectthesize-vs-speedtradeoffwhencompressionanddecompressingdatastreamsorfiles.

AswithsomeotherpropertiesontheZipFileclass,likePassword,Encryption,andZipErrorAction,settingthispropertyonaZipFileinstancewillcausethespecifiedCompressionLeveltobeusedonallZipEntryitemsthataresubsequentlyaddedtotheZipFileinstance.IfyousetthispropertyafteryouhaveaddeditemstotheZipFile,butbeforeyouhavecalledSave(),thoseitemswillnotusethespecifiedcompressionlevel.

Ifyoudonotsetthisproperty,thedefaultcompressionlevelisused,

whichnormallygivesagoodbalanceofcompressionefficiencyandcompressionspeed.Insometests,usingBestCompressioncandoublethetimeittakestocompress,whiledeliveringjustasmallincreaseincompressionefficiency.Thisbehaviorwillvarywiththetypeofdatayoucompress.Ifyouareindoubt,justleavethissettingalone,andacceptthedefault.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileCompressionMethodC#

IonicZipLibraryv1.9.1.6CompressionMethodProperty

Thecompressionmethodforthezipfile.

DeclarationSyntaxC# VisualBasic VisualC++

publicCompressionMethodCompressionMethod{get;set

PublicPropertyCompressionMethodAsCompressionMethod Get Set

public:propertyCompressionMethodCompressionMethod{ CompressionMethodget(); voidset(CompressionMethodvalue);}

Remarks

Bydefault,thecompressionmethodisCompressionMethod.Deflate.

SeeAlsoCompressionMethod

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileContainsEntry(String)C#

IonicZipLibraryv1.9.1.6ContainsEntryMethod(name)

ReturnstrueifanentrybythegivennameexistsintheZipFile.

DeclarationSyntaxC# VisualBasic VisualC++

publicboolContainsEntry( stringname)

PublicFunctionContainsEntry(_ nameAsString_)AsBoolean

public:boolContainsEntry( String^name)

Parametersname(String)

thenameoftheentrytofind

ReturnValuetrueifanentrywiththegivennameexists;otherwisefalse.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/s1wwdcbfhttp://msdn2.microsoft.com/en-us/library/s1wwdcbfmailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileCountIonicZipLibraryv1.9.1.6CountProperty

ReturnsthenumberofentriesintheZiparchive.

DeclarationSyntaxC# VisualBasic VisualC++

publicintCount{get;}

PublicReadOnlyPropertyCountAsInteger Get

public:propertyintCount{ intget();}

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dhttp://msdn2.microsoft.com/en-us/library/td2s409dmailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileDefaultEncodingIonicZipLibraryv1.9.1.6DefaultEncodingProperty

Thedefaulttextencodingusedinziparchives.Itisnumeric437,alsoknownasIBM437.

DeclarationSyntaxC# VisualBasic VisualC++

publicstaticEncodingDefaultEncoding{get;}

PublicSharedReadOnlyPropertyDefaultEncodingAsEncoding Get

public:staticpropertyEncoding^DefaultEncoding{ Encoding^get();}

SeeAlsoProvisionalAlternateEncoding

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/86hf4sb8http://msdn2.microsoft.com/en-us/library/86hf4sb8http://msdn2.microsoft.com/en-us/library/86hf4sb8http://msdn2.microsoft.com/en-us/library/86hf4sb8mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileDispose()IonicZipLibraryv1.9.1.6DisposeMethod

MembersIcon Member Description

Dispose() ClosesthereadandwritestreamsassociatedtotheZipFile,ifnecessary.

Dispose(Boolean) Disposesanymanagedresources,iftheflagisset,thenmarkstheinstancedisposed.Thismethodistypicallynotcalledexplicitlyfromapplicationcode.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#

Copy

ReferenceIonic.ZipZipFileDispose()IonicZipLibraryv1.9.1.6DisposeMethod

ClosesthereadandwritestreamsassociatedtotheZipFile,ifnecessary.

DeclarationSyntaxC# VisualBasic VisualC++

publicvoidDispose()

PublicSubDispose

public:virtualvoidDispose()sealed

RemarksTheDispose()methodisgenerallyemployedimplicitly,viaausing(..){..}statement.(Using...EndUsinginVB)Ifyoudonotemployausingstatement,insurethatyourapplicationcallsDispose()explicitly.Forexample,inaPowershellapplication,oranapplicationthatusestheCOMinteropinterface,youmustcallDispose()explicitly.

ExamplesThisexampleextractsanentryselectedbyname,fromtheZipfiletotheConsole.

C#

using(ZipFilezip=ZipFile.Read(zipfile)){foreach(ZipEntryeinzip){if(WantThisEntry(e.FileName))zip.Extract(e.FileName,Console.OpenStandardOutput());

Copy

}}//Dispose()iscalledimplicitlyhere.

VB.NET

UsingzipAsZipFile=ZipFile.Read(zipfile)DimeAsZipEntryForEacheInzipIfWantThisEntry(e.FileName)Thenzip.Extract(e.FileName,Console.OpenStandardOutput())EndIfNextEndUsing'Disposeisimplicitycalledhere

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

C#ReferenceIonic.ZipZipFileDispose(Boolean)

IonicZipLibraryv1.9.1.6DisposeMethod(disposeManagedResources)

Disposesanymanagedresources,iftheflagisset,thenmarkstheinstancedisposed.Thismethodistypicallynotcalledexplicitlyfromapplicationcode.

DeclarationSyntaxC# VisualBasic VisualC++

protectedvirtualvoidDispose( booldisposeManagedResources)

ProtectedOverridableSubDispose(_ disposeManagedResourcesAsBoolean_)

protected:virtualvoidDispose( booldisposeManagedResources)

ParametersdisposeManagedResources(Boolean)

indicateswhetherthemethodshoulddisposestreamsornot.

RemarksApplicationsshouldcalltheno-argDisposemethod.

[email protected],DinoChiesaAssembly:Ionic.Zip(Module:Ionic.Zip)Version:1.9.1.8(1.9.1.8)

http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50http://msdn2.microsoft.com/en-us/library/a28wyd50mailto:dpchiesa%40hotmail.com?Subject=Ionic Zip Library v1.9.1.6

ReferenceIonic.ZipZipFileEmitTimesInUnixFormatWhenSaving

C#

IonicZipLibrary

v1.9.1.6EmitTimesInUnixFormatWhenSavingProperty

SpecifieswhethertheCreation,Access,andModifiedtimesforentriesadd