Welcome to ComponentOne Zip for .NET

ComponentOne Zip for .NET

Welcome to ComponentOne Zip for .NET

Previous Next

ComponentOne Zip™ for .NET implements several classes that allow you to add data compression to your applications.

If you like Zip for .NET, you can check out our other products by visiting our web site at www.componentone.com.

ComponentOne has a user-friendly distribution policy. We want every Visual Studio programmer to get copies of our products and try them for as long as they want. Those who like the tools and find them useful can buy licenses at reasonable prices. The only restriction is that unlicensed copies of the software will display a ComponentOne banner when they are loaded, as a friendly reminder that we do expect people to pay for the software if they use it on a regular basis.

We are confident that you will like Zip For .NET. If you have any suggestions or ideas for new features that you'd like to see included in a future version, or ideas for new controls, please call us or write:

Corporate Headquarters

ComponentOne LLC
4516 Henry Street
Suite 500
Pittsburgh, PA 15213 USA
412.681.4343
412.681.4384 (Fax)

http://www.componentone.com

End-User License Agreement

Redistributable Files

Technical Support

Namespaces

Adding a Reference to the C1Zip Assembly


End-User License Agreement

End-User License Agreement

IMPORTANT-READ CAREFULLY: This End User License Agreement (this "EULA") contains the terms and conditions regarding your use of the SOFTWARE (as defined below). This EULA contains material limitations to your rights in that regard. You should read this EULA carefully and treat it as valuable property.

I. THIS EULA.

1.

Software Covered by this EULA. This EULA governs your use of the ComponentOne, LLC ("C1") software product(s) enclosed or otherwise accompanied herewith (individually and collectively, the "SOFTWARE"). The term "SOFTWARE" includes, to the extent provided by C1: 1) any revisions, updates and/or upgrades thereto; 2) any data, image or executable files, databases, data engines, computer software, or similar items customarily used or distributed with computer software products; 3) anything in any form whatsoever intended to be used with or in conjunction with the SOFTWARE; and 4) any associated media, documentation (including physical, electronic and on-line) and printed materials (the "Documentation").

2.

This EULA is a Legally Binding Agreement Between You and C1. If you are acting as an agent of a company or another legal person, such as an officer or other employee acting for your employer, then "you" and "your" mean your principal, the entity or other legal person for whom you are acting. However, importantly, even if you are acting as an agent for another, you may still be personally liable for violation of federal and State laws, such as copyright infringement.

This EULA is a legally binding agreement between you and C1. You intend to be legally bound to this EULA to the same extent as if C1 and you physically signed this EULA. By installing, copying, or otherwise using the SOFTWARE, you agree to be bound by the terms and conditions contained in this EULA. If you do not agree to all of the terms and conditions contained in this EULA, you may not install or use the SOFTWARE. If, for whatever reason, installation has begun or has been completed, you should cancel installation or un-install the SOFTWARE, as the case may be. (You may click on the "exit" button or its equivalent to immediately abort installation.) If you do not agree to all of these terms and conditions, then you must promptly return the SOFTWARE to the place of business from which you obtained it in accordance with any return policies of such place of business. Return policies may vary between or among resellers, and you must comply with your particular reseller's return policies as agreed at the point of purchase. If the place of business from which you purchased the SOFTWARE does not honor a complete refund for a period of thirty (30) days from the date of proof of purchase, then you may return the SOFTWARE directly to C1 for a period of thirty (30) days from the date of your purchase. To return the product directly to C1, you must obtain a C1 Return Authorization Number by contacting C1, and you must forward all items purchased, including the proof of purchase, directly to C1. The return must be postage-prepaid, and post-marked within thirty (30) days from the proof of purchase, time being of the essence. The return option to C1 is only available to the original purchaser of an unopened factory packaged item.

II. YOUR LICENSE TO DEVELOP AND TO DISTRIBUTE.

As provided in more detail below, this EULA grants you two licenses: 1) a license to use the SOFTWARE to develop other software products (the "Development License"); and 2) a license to use and/or distribute the Developed Software (the "Distribution License"). Both of these licenses (individually and collectively, the "Licenses") are explained and defined in more detail below.

1.

Definitions. The following terms have the respective meanings as used in this EULA:

"Network Server" means a computer with one or more computer central processing units (CPU's) that operates for the purpose of serving other computers logically or physically connected to it, including, but not limited to, other computers connected to it on an internal network, intranet or the Internet. "Web Server" means a type of Network Server that serves other computers more particularly connected to it over an intranet or the Internet.

"Developed Software" means those computer software products that are developed by or through the use of the SOFTWARE. "Developed Web Server Software" means those Developed Software products that reside logically or physically on at least one Web Server and are operated (meaning the computer software instruction set is carried out) by the Web Server's central processing unit(s) (CPU). "Developed Legacy Software" means those Developed Software products that are not Developed Web Server Software, including, for example, stand-alone applications and applications accessed by a file server only. "Redistributable Files" means the SOFTWARE files or other portions of the SOFTWARE that are provided by C1 and are identified as such in the Documentation for distribution by you with the Developed Software. "Developer" means a human being or any other automated device using the SOFTWARE in accordance with the terms and conditions of this EULA.

"Developer Seat License" means that each Developer using or otherwise accessing the programmatic interface or the SOFTWARE must obtain the right to do so by purchasing a separate End User License. "Network Server CPU License" means that a separate End User License must be purchased for each CPU operating the computer software at issue in the reference.

“Source Code” shall mean computer software code or programs in human readable format, such as a printed listing of such a program written in a high-level computer language. The term "Source Code" includes, but is not limited to, documents and materials in support of the development effort of the SOFTWARE, such as flow charts, pseudo code and program notes.

2.

Your Development License. You are hereby granted a limited, royalty-free, non-exclusive right to use the SOFTWARE to design, develop, and test Developed Software, on the express condition that, and only for so long as, you fully comply with all terms and conditions of this EULA.

The SOFTWARE is licensed to you on a Developer Seat License basis.

The Developer Seat License means that you may perform a single install of the SOFTWARE for use in designing, testing and creating Developed Software by a single Developer on a single computer with a single set of input devices, so long as such computer is used only by one Developer. Conversely, you may not install or use the SOFTWARE on a computer that is a network server or a computer at which the SOFTWARE is used by more than one Developer. You may not network the SOFTWARE or any component part of it, where it is or may be used by more than one Developer unless you purchase an additional Development License for each Developer. You must purchase another separate license to the SOFTWARE in order to add additional developer seats, whether the additional developers are accessing the SOFTWARE in a stand-alone environment or on a computer network. If the SOFTWARE is used to create Developed Web Server Software, then you may perform a single install of the SOFTWARE for use in designing, testing and creating Developed Web Server Software by a single Developer on a single computer or Network Server, either with a single CPU only. An additional Network Server CPU License is required for each additional CPU on the single computer or Network Server, as the case may be, upon which the SOFTWARE and/or the Developed Web Server Software is installed and a separate license for each separate computer. That is, for Developed Web Server Software, if the computer or Network Server operating the SOFTWARE has 2 CPU's, then you would need to purchase one additional Network Server CPU License (beyond the one Developer Seat License granted in this EULA).

In all cases, you may not use C1's name, logo, or trademarks to market your Developed Software without the express written consent of C1; (b) you must include the following C1 copyright notice in your Developed Software documentation and/or in the "About Box" of your Developed Software, and wherever the copyright/rights notice is located in the Developed Software (“Portions Copyright © ComponentOne, LLC 1991-2002. All Rights Reserved.”); (c) agree to indemnify, hold harmless, and defend C1, its suppliers and resellers, from and against any claims or lawsuits, including attorney's fees that may arise from the use or distribution of your Developed Software; (d) you may use the SOFTWARE only to create Developed Software that is significantly different than the SOFTWARE.

3.

Your Distribution License.

a. License to Distribute Developed Legacy Software. Subject to the terms and conditions in this EULA, you are granted the license to use and to distribute Developed Legacy Software on a royalty-free basis, provided that the Developed Legacy Software incorporates the SOFTWARE as an integral part of the Developed Software in machine-language compiled format (customarily an ".exe", or ".dll", etc.). You may not distribute, bundle, wrap or subclass the SOFTWARE as Developed Software which, when used in a "designtime" development environment, exposes the programmatic interface of the SOFTWARE. You may distribute, on a royalty-free basis, Redistributable Files with Developed Legacy Software only.

b. License to Distribute Developed Web Server Software. Subject to the terms and conditions in this EULA, you are granted the license to use and to distribute Developed Web Server Software, provided that you must purchase one Network CPU License for each CPU operating the Developed Web Server Software (and/or Redistributable Files called or otherwise used directly by the Developed Web Server Software). You may purchase an additional Network CPU License by purchasing an additional separate End User License for the SOFTWARE; one Network CPU License is included in this EULA. Notwithstanding the foregoing, however, you may distribute or transfer, free of royalties, the Redistributable Files (and/or any Developed Legacy Software) to the extent that they are used separately on a single CPU on the client/workstation side of the network served by the Web Server.

4.

Specific Product Limitations. Notwithstanding anything in this EULA to the contrary, if the license you have purchased is for any of the following products, then the following additional limitations will apply:

a. C1 ReportDesigner. C1ReportDesigner includes at least: 1) one dynamic link library (c1.win.c1reportdesigner.dll) file known as C1ReportDesigner Component, 2) one executable (ReportDesigner.exe) file known as C1ReportDesigner Application and, 3) the Source Code of the C1ReportDesigner Application. The C1ReportDesigner Component is subject to the general terms and restrictions set forth in this EULA. The C1ReportDesigner Application is an executable file used to design and prepare reports; the C1ReportDesigner Application may be distributed, free of royalties, only in conjunction with the Developed Software.

Subject to the terms and conditions in this EULA, C1 hereby grants you the right to use the C1ReportDesigner Application Source Code. You are hereby also granted the right to modify such Source Code and to create derivative works that are based on the licensed Source Code. You may distribute the derivative works that you develop, solely in object code format and exclusively in conjunction with and/or as a part of the Developed Software. You are expressly not granted the right to distribute, disclose or otherwise make available to any third party the licensed Source Code, any modified version, derivative work, or any portion thereof, in source code format.

C1 shall retain all right, title and interest in and to the licensed Source Code, and all C1 updates, modifications or enhancements thereof. Nothing herein shall be deemed to transfer any ownership or title rights in and to the licensed Source Code from C1 to you.

SOURCE CODE IS LICENSED TO YOU AS IS. C1 DOES NOT AND SHALL NOT PROVIDE YOU WITH ANY TECHNICAL SUPPORT FOR YOUR SOURCE CODE LICENSE.

b. VS View Reporting Edition. VS View Reporting Edition includes at least one executable file listed as “VSRpt7.exe”, known as “Designer.” The file "VSRpt7.exe”, or any upgrade or future versions of the Designer, are subject to the restrictions set forth in this EULA and may not be distributed with your Developed Software or in any other way.

c. VSForum. VSForum is intended to be installed on a Network Server. C1 grants to you the following rights to the SOFTWARE: a) Installation: You may install one copy of the SOFTWARE on a single Network Server; b) Use: When installed and initialized, the SOFTWARE creates a database file which contains the embodiment of a discussion forum (the database hereinafter referred to as the "Forum"). You may use the SOFTWARE to create one Forum on one Network Server only, which server may be connected at any point to an unlimited number of workstations or computers operating on one or more networks. You are specifically NOT LICENSED to create or operate multiple Forums. To create or to operate more than one FORUM, you must purchase one additional SOFTWARE license for each additional Forum.

d. Doc-to-Help. You may use Doc-To-Help to create online help, manuals or other documentation in electronic or printed format (the "Output Documents"). You may distribute and incorporate in such Output Documents those files identified in the documentation as Redistributable Files. Except for those specific Redistributable Files, you MAY NOT distribute the SOFTWARE, in any format, to others.

e. Studio Products. You may not share the component parts of the Studio Products licensed to you with other Developers, nor may you allow the use and/or installation of such components by other Developers.

5.

Updates/Upgrades; Studio Subscription. Subject to the terms and conditions of this EULA, the Licenses are perpetual. Updates and upgrades to the SOFTWARE may be provided by C1 from time-to-time, and, if so provided by C1, are provided upon the terms and conditions offered at that time by C1 in its sole discretion. C1 may provide updates and upgrades to the SOFTWARE for free or for any charge, at any time or never, and through its chosen manner of access and distribution, all in C1's sole and complete discretion.

C1 licenses certain of its separately-licensed products bundled together in a product suite, called the C1 "Studio" product line (the "Studio Products"). The exact separately-licensed products that are bundled into the Studio Products may change from time-to-time in C1's sole discretion. If the SOFTWARE is identified as a C1 "Studio" product, then the SOFTWARE is one of the Studio Products. The SOFTWARE and the Studio Products are revised from time-to-time (meaning, for example, revised with updates, upgrades and, in the case of Studio products, possibly changes to which specific products are included in the bundle). For you to be entitled to receive any such revisions to the SOFTWARE or the Studio Products, as the case may be, you must have a valid SOFTWARE license or a valid Studio subscription. The original purchaser of the SOFTWARE or of a Studio product receives a one-year subscription from the date of purchase of the SOFTWARE. After one year, the Studio subscription and/or the SOFTWARE license must be renewed to continue to be entitled to receive the SOFTWARE and/or the Studio Products revisions as the case may be.

6.

Serial Number. Within the packaging of the SOFTWARE, a unique serial number (the "Serial Number") is included, which allows for the registration of the SOFTWARE. The Serial Number is subject to the restrictions set forth in this EULA and may not be disclosed or distributed either with your Developed Software or in any other way. The disclosure or distribution of the Serial Number shall constitute a breach of this EULA, the effect of which shall be the automatic termination and revocation of all the rights granted herein.

7.

Evaluation Copy. If you are using an "evaluation copy" or similar version, specifically designated as such by C1 on its website or otherwise, then the Licenses are limited as follows: a) you are granted a license to use the SOFTWARE for a period of thirty (30) days counted from the day of installation (the "Evaluation Period"); b) upon completion of the Evaluation Period, you shall either i) delete the SOFTWARE from the computer containing the installation, or you may ii) contact C1 or one of its authorized dealers to purchase a license of the SOFTWARE, which is subject to the terms and limitations contained herein; and c) any Developed Software may not be distributed or used for any commercial purpose.

III. INTELLECTUAL PROPERTY.

1.

Copyright. You agree that all right, title, and interest in and to the SOFTWARE (including, but not limited to, any images, photographs, animations, video, audio, music, text, and “applets” incorporated into the SOFTWARE), and any copies of the SOFTWARE, and any copyrights and other intellectual properties therein or related thereto are owned exclusively by C1, except to the limited extent that C1 may be the rightful license holder of certain third-party technologies incorporated into the SOFTWARE. The SOFTWARE is protected by copyright laws and international treaty provisions. The SOFTWARE is licensed to you, not sold to you. C1 reserves all rights not otherwise expressly and specifically granted to you in this EULA.

2.

Backups. You may either: (a) copy the SOFTWARE solely for backup or archival purposes; or (b) install the SOFTWARE on a single computer, provided you keep the original solely for backup or archival purposes. Notwithstanding the foregoing, you may not copy the Documentation.

3.

General Limitations. You may not reverse engineer, decompile, or disassemble the SOFTWARE, except and only to the extent that applicable law expressly permits such activity notwithstanding this limitation.

4.

Software Transfers. You may not rent or lease the SOFTWARE. You may transfer the SOFTWARE to another computer, provided that it is completely removed from the computer from which it was transferred. You may permanently transfer all of your rights under the EULA, provided that you retain no copies, that you transfer all the SOFTWARE (including all component parts, the media and printed materials, any dates, upgrades, this EULA and, if applicable, the Certificate of Authenticity), and that the recipient agrees to the terms and conditions of this EULA as provided herein. If the SOFTWARE is an update or upgrade, any transfer must include all prior versions of the SOFTWARE.

5.

Termination. Without prejudice to any other rights it may have, C1 may terminate this EULA and the Licenses if you fail to comply with the terms and conditions contained herein. In such an event, you must destroy all copies of the SOFTWARE and all of its component parts.

6.

Export Restrictions. You acknowledge that the SOFTWARE is of U.S. origin. You acknowledge that the license and distribution of the SOFTWARE is subject to the export control laws and regulations of the United States of America, and any amendments thereof, which restrict exports and re-exports of software, technical data, and direct products of technical data, including services and Developed Software. You agree that you will not export or re-export the SOFTWARE or any Developed Software, or any information, documentation and/or printed materials related thereto, directly or indirectly, without first obtaining permission to do so as required from the United States of America Department of Commerce's Bureau of Export Administration ("BXA"), or other appropriate governmental agencies, to any countries, end-users, or for any end-uses that are restricted by U.S. export laws and regulations, and any amendments thereof, which include, but are not limited to, the following:

Restricted Countries: Restricted Countries currently include, but are not necessarily limited to Cuba, Iran, Iraq, Libya, Montenegro, North Korea, Serbia, Sudan, and Syria.

Restricted End-Users: Any End-User whom you know or have reason to know will use SOFTWARE or Developed Software in the design, development, or production of missiles and missile technology, nuclear weapons and weapons technology, or chemical and biological weapons. Any national of any of the Restricted Countries, wherever located, who intends to transmit or transport the SOFTWARE or Developed Software to one of the Restricted Countries.

Restricted End-Uses: Any use of SOFTWARE and Developed Software related to the design, development, or production of missiles and missile technology, nuclear weapons and weapons technology, or chemical and biological weapons.

These restrictions change from time to time. You represent and warrant that neither the BXA nor any other United States federal agency has suspended, revoked or denied your export privileges. C1 acknowledges that it shall use reasonable efforts to supply you with all reasonably necessary information regarding the SOFTWARE and its business to enable you to fully comply with the provisions of this Section. If you have any questions regarding your obligations under United States of America export regulations, you should contact the Bureau of Export Administration, United States Department of Commerce, Exporter Counseling Division, Washington DC. U.S.A. (202) 482-4811, http://www.bxa.doc.gov.

7.

U.S. Government Restricted Rights. The SOFTWARE and documentation are provided with RESTRICTED RIGHTS. For solicitations issued before December 1, 1995, by the United States of America, its agencies and/or instrumentalities (the "Government"), other than the Department of Defense, the use, duplication or disclosure of the software and documentation provided to the Government under this EULA shall be subject to the RESTRICTED RIGHTS as set forth in subparagraphs (c)(1) and (2) of the Commercial Computer Software - Restricted Rights clause at 48 CFR ch.1 52.227-19. For solicitations issued before September 29, 1995, by the Department of Defense, the use, duplication or disclosure of the software and documentation provided under this EULA shall be subject to the RESTRICTED RIGHTS as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at 48 CFR ch.2 252.227-7013. You will comply with any requirements of the Government to obtain such RESTRICTED RIGHTS protection, including without limitation, the placement of any restrictive legends on the SOFTWARE, and any license agreement used in connection with the distribution of the SOFTWARE. Manufacturer is ComponentOne, LLC, 4516 Henry Street, Suite 501, Pittsburgh, Pennsylvania 15213 USA. For solicitations issued by the Government on or after December 1, 1995 and the Department of Defense on or after September 29, 1995, the only rights provided in the software and documentation provided herein shall be those contained in this EULA. Under no circumstances shall C1 be obligated to comply with any Governmental requirements regarding the submission of or the request for exemption from submission of cost or pricing data or cost accounting requirements. For any distribution of the SOFTWARE that would require compliance by C1 with the Government's requirements relating to cost or pricing data or cost accounting requirements, you must obtain an appropriate waiver or exemption from such requirements for the benefit of C1 from the appropriate Government authority before the distribution and/or license of the SOFTWARE to the Government.

IV. WARRANTIES AND REMEDIES.

1.

Limited Warranty. C1 warrants that the original media, if any, are free from defects for ninety (90) days from the date of delivery of the SOFTWARE. EXCEPT AS OTHERWISE PROVIDED IN THE PRECEDING SENTENCE, AND TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, C1 EXPRESSLY DISCLAIMS ANY WARRANTY FOR THE SOFTWARE, DOCUMENTATION AND ANYTHING ELSE PROVIDED BY C1 HEREBY AND C1 PROVIDES THE SAME IN “AS IS” CONDITION WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK ARISING OUT OF USE OR PERFORMANCE OF THE SOFTWARE AND DOCUMENTATION REMAINS WITH YOU. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS. YOU MAY HAVE OTHERS WHICH VARY FROM STATE TO STATE.

2.

Limited Remedy. C1's entire liability and your exclusive remedy under this EULA shall be, at C1's sole option, either (a) return of the price paid for the SOFTWARE; (b) repair the SOFTWARE through updates distributed online or otherwise in C1's discretion; or (c) replace the SOFTWARE with its reasonable, provided that you return the SOFTWARE in the same manner as provided in Section I.2 for return of the SOFTWARE for non-acceptance of this EULA. Any media for any repaired or replacement SOFTWARE will be warranted for the remainder of the original warranty period or thirty (30) days, whichever is longer. THESE REMEDIES ARE NOT AVAILABLE OUTSIDE OF THE UNITED STATES OF AMERICA. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL C1 BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFIT, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE, EVEN IF C1 HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME STATES/JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES IN CERTAIN CASES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU.

V. MISCELLANEOUS.

1.

This is the Entire Agreement. This EULA (including any addendum or amendment to this EULA included with the SOFTWARE) is the final, complete and exclusive statement of the entire agreement between you and C1 relating to the SOFTWARE. This EULA supersedes any prior and contemporaneous proposals, purchase orders, advertisements, and all other communications in relation to the subject matter of this EULA, whether oral or written. No terms or conditions, other than those contained in this EULA, and no other understanding or agreement which in any way modifies these terms and conditions, shall be binding upon the parties unless entered into in writing executed between the parties, or by other non-oral manner of agreement whereby the parties objectively and definitively act in a manner to be bound (such as by continuing with an installation of the SOFTWARE, "clicking-through" a questionnaire, etc.) Employees, agents and other representatives of C1 are not permitted to orally modify this EULA.

2.

You Indemnify C1. You agree to indemnify, hold harmless, and defend C1 and its suppliers and resellers from and against any and all claims or lawsuits, including attorney's fees, that arise or result from this EULA.

3.

Interpretation of this EULA. If for any reason a court of competent jurisdiction finds any provision of this EULA, or any portion thereof, to be unenforceable, that provision of this EULA will be enforced to the maximum extent permissible so as to effect the intent of the parties, and the remainder of this EULA will continue in full force and effect. Formatives of defined terms shall have the same meaning of the defined term. Failure by either party to enforce any provision of this EULA will not be deemed a waiver of future enforcement of that or any other provision. Except as otherwise required or superseded by law, this EULA is governed by the laws of the Commonwealth of Pennsylvania, without regard to its conflict of laws principles. The parties consent to the personal jurisdiction and venue of the Commonwealth of Pennsylvania, in the County of Allegheny, and agree that any legal proceedings arising out of this EULA shall be conducted solely in such Commonwealth. If the SOFTWARE was acquired outside the United States, then local law may apply.


Redistributable Files

Redistributable Files

ComponentOne Zip for .NET is developed and published by ComponentOne LLC. You may use it for development with Microsoft Visual Studio or any other programming environment. You may also distribute the following control files, royalty free, with any application you develop:

•

C1.C1Zip.dll

Groups of multiple developers may be interested in acquiring ComponentOne product site licenses. Please contact ComponentOne for details.


Technical Support

Technical Support

Zip for .NET is developed and supported by ComponentOne LLC, a company formed by the merger of APEX Software Corporation and VideoSoft. You can obtain technical support using any of the following methods:


ComponentOne Web site

ComponentOne Web site

The ComponentOne Web site at http://www.componentone.com/ provides a wealth of information and software downloads for Zip for .NET users, including:

•

Descriptions of the various support options available through the ComponentOne Service Team.

•

Answers to frequently asked questions (FAQ's) about our products, organized by functionality. Please consult the FAQ's before contacting us directly, as this can save you time and also introduce you to other useful information pertaining to our products.

•

Free product updates, which provide you with bug fixes and new features.


Internet e-mail

Internet e-mail

For technical support through the Internet, e-mail us at:

support.c1zip@componentone.com

To help us provide you with the best support, please include the following information when contacting ComponentOne:

•

Your ComponentOne product serial number.

•

The version and name of your operating system.

•

Your development environment and its version.

For more information on technical support, go to:

http://www.componentone.com/support


Peer-to-Peer newsgroup

Peer-to-Peer newsgroup

ComponentOne also sponsors peer-to-peer newsgroups for users. ComponentOne does not offer formal technical support in this newsgroup, but instead sponsors it as a forum for users to post and answer each other's questions regarding our products. However, ComponentOne may monitor the newsgroups to ensure accuracy of information and provide comments when necessary. You can access the newsgroup from the ComponentOne Web site at http://www.componentone.com/newsgroups.


Namespaces

Namespaces

Namespaces organize the objects defined in an assembly. Assemblies can contain multiple namespaces, which can in turn contain other namespaces. Namespaces prevent ambiguity and simplify references when using large groups of objects such as class libraries.

The namespace for the C1Zip component is C1.C1Zip. The following code fragment shows how to declare a C1Zip component using the fully qualified name for this class:

Dim zip As C1.C1Zip.C1Zip

Namespaces address a problem sometimes known as namespace pollution, in which the developer of a class library is hampered by the use of similar names in another library. These conflicts with existing components are sometimes called name collisions.

For example, if you create a new class named C1ZipFile, you can use it inside your project without qualification. However, the C1Zip assembly also implements a class called C1ZipFile. So, if you want to use the C1Zip class in the same project, you must use a fully qualified reference to make the reference unique. If the reference is not unique, Visual Studio .NET produces an error stating that the name is ambiguous. The following code snippet demonstrates how to declare these objects:

' Define a new C1ZipFile object (custom C1ZipFile class)

Dim MyC1ZipFile as C1ZipFile

' Define a new C1Zip.C1ZipFile object.

Dim ZipFile as C1.C1Zip.C1ZipFile

Fully qualified names are object references that are prefixed with the name of the namespace where the object is defined. You can use objects defined in other projects if you create a reference to the class (by choosing Add Reference from the Project menu) and then use the fully qualified name for the object in your code.

Fully qualified names prevent naming conflicts because the compiler can always determine which object is being used. However, the names themselves can get long and cumbersome. To get around this, you can use the Imports statement (using in C#) to define an alias — an abbreviated name you can use in place of a fully qualified name. For example, the following code snippet creates aliases for two fully qualified names, and uses these aliases to define two objects:

Imports C1File = C1.C1Zip.C1ZipFile

Imports MyFile = MyProject.C1ZipFile

Dim f1 As C1File

Dim f2 As MyFile

If you use the Imports statement without an alias, you can use all the names in that namespace without qualification, provided they are unique to the project.


Adding a Reference to the C1Zip Assembly

Adding a Reference to the C1Zip Assembly

When you install C1Zip, a new component does not appear in the Visual Studio’s toolbox. Therefore, to use C1Zip, you must reference the C1Zip assembly in your project. To use the C1Zip component:

1.

Select the Add Reference option from the Project menu of your project.

2.

Select the C1.C1Zip assembly from the list, or browse to find the C1.C1Zip.dll file.

3.

Double-click the form caption area to open the code window. At the top of the file, add the following Imports statements (using in C#):

Imports System.IO

Imports C1.C1Zip

NOTE: This makes the objects defined in the C1Zip and System.IO assemblies visible to the project and saves a lot of typing.


Overview

Overview

The classes in the C1Zip library are divided into three levels:

Level | Main Classes | Description
High | C1ZipFile, C1ZipEntry, C1ZipEntryCollection | Use these classes to create, open, and manage ZIP files. You can inspect the contents of zip files, test their integrity, add, delete, and extract entries to and from ZIP files.
Medium | C1ZStreamReader, C1ZStreamWriter | Use these classes to compress and expand data into and out of regular .NET streams (including memory, file, and network streams).
Low | ZStream | This is the lowest level class in C1Zip. It is a 100% C# implementation of Zlib, the popular data-compression library written by Jean-loup Gailly and Mark Adler. ZStream is used by the higher level classes in C1Zip.


The C1ZipFile, C1ZipEntry and C1ZipEntryCollection Classes

The C1ZipFile, C1ZipEntry and C1ZipEntryCollection Classes

These are the highest level classes in the C1Zip library. They allow you to create and manage zip regular zip files. Using zip files to store application data provides the following benefits:

1.

You can consolidate many files into one, making application deployment easier.

2.

You can compress the data, saving disk space and network bandwidth.

3.

The zip format is an open standard, supported by many popular applications.

The C1ZipFile class encapsulates a zip file. After you create a C1ZipFile object, you can attach it to an existing zip file or tell it to create a new empty zip file for you. For example:

// create a C1ZipFile object:

C1ZipFile myZip = new C1ZipFile();

// create a new (empty) zip file

myZip.Create("New.zip");

// open an existing zip file

myZip.Open("Old.zip");

After you have created or opened a zip file, use the Entries collection to inspect the contents of the zip file, or to add, expand, and delete entries. For example:

myZip.Entries.Add("MyData.txt");

myZip.Entries.Add("MyData.xml");

myZip.Entries.Add("MyData.doc");

foreach (C1ZipEntry zipEntry in myZip.Entries)

Console.WriteLine(zipEntry.Name);

The C1ZipEntry class exposes properties and methods that describe each entry, including its original file name, size, compressed size, etc. It also has an OpenReader method that returns a stream object, so you can read the entry contents without expanding it first.


The C1ZStreamReader and C1ZStreamWriter Classes

The C1ZStreamReader and C1ZStreamWriter Classes

These classes allow you to use data compression on any .NET streams, not only in zip files.

To use C1ZStreamReader and C1ZStreamWriter objects, attach them to regular streams and read or write the data through them. The data is compressed (or expanded) on the fly into (or out of) the underlying stream.

This design allows great integration with native .NET streams. The diagram below illustrates how it works:

For example, the code below saves an ADO.NET DataTable object into a stream and then reads it back:

// save DataTable into compressed stream

BinaryFormatter bf = new BinaryFormatter();

FileStream fout = new FileStream("test.tmp", FileMode.Create);

bf.Serialize(fout, DataTableOut);

fout.Close();

// read compressed data

FileStream fin = new FileStream("test.tmp", FileMode.Open);

DataTable DataTableIn = bf.Deserialize(fin)

To add data compression, you would simply add two lines of code:

// save DataTable into compressed stream

BinaryFormatter bf = new BinaryFormatter();

FileStream fout = new FileStream("test.tmp", FileMode.Create);

C1ZStreamWriter compressor = new C1ZStreamWriter(fout);

bf.Serialize(compressor, DataTableOut);

fout.Close();

// read compressed data

FileStream fin = new FileStream("test.tmp", FileMode.Open);

C1ZStreamReader decompressor = new C1ZStreamReader(fin);

DataTable DataTableIn = bf.Deserialize(decompressor)


The ZStream Class

The ZStream Class

This is the lowest-level class in the C1Zip library, and it is used extensively by the higher-level classes described above.

Most users won't ever need to use ZStream directly. It is the most flexible, but hardest to use component in the C1Zip library.

ZStream is a C# implementation of the ZLIB library. ZLIB is an open-source library written by Jean-loup Gailly and Mark Adler. For more information on ZLIB, check http://www.info-zip.org/ or http://www.gzip.org/.


Using C1Zip

Using C1Zip

The following sections contain tutorials that illustrate some of the main features in the C1Zip library. The tutorials walk you through the creation of several simple projects, describing each step in detail. The distribution CD contains more sophisticated samples that can be used as a reference.

The tutorials are:

Compressing Data in Memory | Shows how you can compress and expand arbitrary data in memory. This technique is useful in any situation where you keep memory streams while the application is running. By compressing the streams, you can reduce the memory requirements for your application.
Compressing Files | Shows how you can compress individual files so they take up less disk space and are less exposed to access by users. Note that these are not Zip files, just individual compressed files. The last tutorial covers Zip files.
Compressed Serialization | Shows how you can combine C1Zip with .NET serialization to save objects into streams that are a fraction of the regular size. If you are serializing objects into XML streams, the savings in disk space and network bandwidth can be huge.
Handling Zip files | Shows how you can open, inspect, add, and remove files in a Zip archive. Using the Zip format for your application storage needs has several advantages: it is an open-standard, well-documented, space-efficient format.

Compressing Data in Memory

Compressing Files

Compressed Serialization

Handling Zip Files


Compressing Data in Memory

Compressing Data in Memory

This tutorial shows how you can compress basic data types such as strings and doubles into memory streams, and expand the data back when you read it from the streams.

Here is what the final application will look like:

Step 1: Create the main form.

Start a new Visual Basic project and add the following controls to the form:

1.

Four CommandButton controls along the left edge of the form, with the captions shown in the picture above. Set the Enabled property of the "Decompress" buttons to false (they cannot be used until we have some compressed data to expand).

2.

A TextBox on the upper-right of the form. Set the MultiLine property to true, and use the Lines property to paste some text to use as an initial value.

3.

A Label control below the text box.

Step 2: Add a reference to the C1Zip assembly.

Go to the Solution Explorer window, right-click on References, and select the "Add Reference…" menu option. Select the C1.C1Zip assembly from the list, or browse to find the C1.C1Zip.dll file.

Now double-click the form caption area to open the code window. At the top of the file, add the following statements:

Imports System.IO

Imports C1.C1Zip

This makes the objects defined in the C1Zip assembly visible to the project and saves a lot of typing.

Step 3: Add code to compress strings.

Double-click the "Compress String" command button to open the code window, then type (or copy) the following code to handle the click event:

Dim m_CompressedString As Byte()

Private Sub btnCompressString_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompressString.Click

' compress the string

Dim ticks As Long = DateTime.Now.Ticks

m_CompressedString = CompressString(textBox1.Text)

' tell user how long it took

Dim ms As Integer

ms = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond

Dim lenBefore As Integer = textBox1.Text.Length * 2

Dim lenAfter As Integer = m_CompressedString.Length

Dim msg As String

msg = String.Format( "Compressed from {0} bytes to " & "{1} bytes in {2} milliseconds.", lenBefore, lenAfter, ms)

MessageBox.Show(msg, "Compressed", MessageBoxButtons.OK, MessageBoxIcon.Information)

' we can now expand it

btnExpandString.Enabled = True

End Sub

The main lines are the ones marked in boldface. The first one declares a member variable called m_CompressedString which will be used to hold the compressed data (encoded as a byte array). The second calls a utility function CompressString that compresses a given string into a byte array that can later be expanded to restore the original string. The remainder of the code is used to measure how long the compression process took and to show a dialog box with statistics.

(Note that the lenBefore variable is calculated as the length of the string times two. This is because .NET strings are Unicode, and each character actually takes up two bytes.)

Here is the code that implements the CompressString function:

Public Function CompressString(ByVal str As String) As Byte()

' open memory stream

Dim ms As MemoryStream = New MemoryStream()

' attach compressor stream to memory stream

Dim sw As C1ZStreamWriter = New C1ZStreamWriter(ms)

' write data into compressor stream

Dim writer As StreamWriter = New StreamWriter(sw)

writer.Write(str)

' flush any pending data

writer.Flush()

' return the memory buffer

CompressString = ms.ToArray()

End Function

The function starts by creating a new memory stream. This stream will automatically allocate a memory buffer to hold the compressed data.

Next, the function creates a C1ZStreamWriter object and attaches it to the new memory stream. Any data written to the C1ZStreamWriter object will be compressed and written to the memory stream.

The C1ZStreamWriter object only supplies the basic Stream methods for writing bytes and byte arrays. To be able to write other basic types such as strings, integers, etc., we attach a StreamWriter object to the C1ZStreamWriter. Here's a diagram that shows how this works:

After the StreamWriter is set up, all we need to do is call its Write method to write the string into the compressed memory stream. When done writing, we also call the Flush method to make sure all cached input is written out.

Finally, the code uses the ToArray method to return the byte array that was created by the memory stream.

Step 4: Add code to expand strings.

To expand the string, we need to follow the reverse sequence of steps used to compress. Double-click the "Decompress String" button to open the code window, then type or copy the following code to handle the click event:

Private Sub btnExpandString_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExpandString.Click

' expand the string

Dim ticks As Long = DateTime.Now.Ticks

textBox1.Text = ExpandString(m_CompressedString)

' tell user how long it took

Dim ms As Integer = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond

Dim lenBefore As Integer = m_CompressedString.Length

Dim lenAfter As Integer = textBox1.Text.Length * 2

Dim msg As String

msg = String.Format("Expanded from {0} bytes to {1} bytes " & "in {2} milliseconds.", lenBefore, lenAfter, ms)

MessageBox.Show(msg, "Expanded", MessageBoxButtons.OK, MessageBoxIcon.Information)

End Sub

The main line is the one in bold. It calls the utility function ExpandString that takes a byte array and returns the original string. Here's the code:

Public Function ExpandString(ByVal buffer As Byte()) As String

' turn buffer into a memory stream

Dim ms As MemoryStream = New MemoryStream(buffer)

' attach decompressor stream to memory stream

Dim sr As C1ZStreamReader = New C1ZStreamReader(ms)

' read uncompressed data

Dim reader As StreamReader = New StreamReader(sr)

ExpandString = reader.ReadToEnd()

End Function

If you run the project now, you can already experiment with string compression and decompression. You can change the text in the text box, or paste new content into it, then compress and expand the string to see how much it compresses.

Step 5: Add code to compress binary data.

Compressing binary data is just as easy as compressing strings. The only difference is that instead of attaching a StreamWriter object to the compressor stream, you attach a BinaryWriter object.

Double-click the "Compress Data" button and add the following code to handle the click event:

Private m_CompressedData As Byte()

Private Sub btnCompressData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompressData.Click

' open memory stream

Dim ms As MemoryStream = New MemoryStream()

' attach compressor stream to memory stream

Dim sw As C1ZStreamWriter = New C1ZStreamWriter(ms)

' attach BinaryWriter to the compressor stream

Dim bw As BinaryWriter = New BinaryWriter(sw)

' write a bunch of numbers into the stream

Dim i As Integer

Dim count As Integer = 1000

bw.Write(count)

For i = 0 To count – 1

Dim a As Double = i * Math.PI / 180.0

bw.Write(i)

bw.Write(a)

bw.Write(Math.Sin(a))

bw.Write(Math.Cos(a))

Next

' flush any pending output

bw.Flush()

' save the compressed data

m_CompressedData = ms.ToArray()

' done

Dim msg As String

msg =String.Format("Generated table with {0} points," & " saved into {1} bytes", count, m_CompressedData.Length)

label1.Text = msg

' we can now expand it

btnExpandData.Enabled = True

End Sub

The code starts by declaring a member variable called m_CompressedData which will be used to hold the compressed data (encoded as a byte array).

Then it sets up the MemoryStream, C1ZStreamWriter, and BinaryWriter objects as before (the only difference is we're now using a BinaryWriter instead of a StreamWriter).

Next, the code writes data into the stream using the Write method. The BinaryWriter object overloads this method so you can write all basic object types into streams. Finally, the Flush method is used as before, to make sure any cached data is written out to the compressed stream.

Step 6: Add code to expand the binary data.

Expanding the compressed binary data is just a matter of setting up the decompressor stream and reading the data like you would read it from a regular stream.

Double-click the "Decompress Data" button and add the following event handler code:

Private Sub btnExpandData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExpandData.Click

' open memory stream on saved data

Dim ms As MemoryStream = New MemoryStream(m_CompressedData)

' attach decompressor stream to memory stream

Dim sr As C1ZStreamReader = New C1ZStreamReader(ms)

' read uncompressed data

Dim i As Integer

Dim br As BinaryReader = New BinaryReader(sr)

Dim count As Integer = br.ReadInt32()

For i = 0 To count – 1

Dim deg As Integer = br.ReadInt32()

Dim rad As Double = br.ReadDouble()

Dim sin As Double = br.ReadDouble()

Dim cos As Double = br.ReadDouble()

Next

' done

Dim msg As String

msg = String.Format("Read table with {0} points " & "from stream with {1} bytes.", count, m_CompressedData.Length)

label1.Text = msg

End Sub

The code reads the data but does not display it. You can step through it in debug mode to make sure the data being read is the same that was written in.

If you run the project and click the compress/decompress data buttons, you will see that the data is saved in an array with 14,125 bytes. To save this data in a regular stream, it would take [4 + 1000 * (4 + 8 * 3)] = 28,004 bytes. So we compressed it to about half the original size.

This is the end of this tutorial.


Compressing Files

Compressing Files

This tutorial shows how you can compress and expand individual files. Note that these are not zip files, they are just compressed streams on disk. Zip files are covered in the Handling Zip Files tutorial.

Here is what the final application will look like:

Step 1: Create the main form.

Start a new Visual Basic project and add the following controls to the form:

1.

Two CommandButton controls along the left edge of the form, with the captions shown in the picture above. Set the Enabled property of the "Expand Files" button to false (it cannot be used until we have some compressed files to expand).

2.

A Label control on the right of the buttons. This control will display statistics about the compression/expanding process.

Step 2: Add a reference to the C1Zip assembly.

Go to the Solution Explorer window, right-click on References, and select the "Add Reference…" menu option. Select the C1.C1Zip assembly from the list, or browse to find the C1.C1Zip.dll file.

Now double-click the form caption area to open the code window. At the top of the file, add the following statements:

Imports System.IO

Imports C1.C1Zip

This makes the objects defined in the C1Zip and System.IO assemblies visible to the project and saves a lot of typing.

Step 3: Define the directory names for the compressed and expanded files.

In the code window of the form, define the following constants:

Private Const DIR_COMP = "\compressed"

Private Const DIR_EXP = "\expanded"

These are the directory names where the compressed and expanded files will be stored (relative to the directory where the tutorial application is located on your disk).

Step 4: Add code to compress files.

Double-click the "Compress Files" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnCompress_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompress.Click

' get application directory

Dim appPath As String = Application.ExecutablePath

Dim i As Integer = appPath.IndexOf("\bin\")

If i > 0 Then appPath = appPath.Substring(0, i)

' create directory for compressed files

If (Directory.Exists(appPath + DIR_COMP)) Then

Directory.Delete(appPath + DIR_COMP, True)

End If

Directory.CreateDirectory(appPath + DIR_COMP)

' prepare to collect compression statistics

Dim count As Long

Dim size As Long

Dim sizeCompressed As Long

Dim ticks As Long = DateTime.Now.Ticks

' compress all files in application dir into compressed dir

Dim files As String() = Directory.GetFiles(appPath)

Dim srcFile As String

For Each srcFile In files

Dim dstFile As String

dstFile = appPath + DIR_COMP + "\" + Path.GetFileName(srcFile) + ".cmp"

' compress file

CompressFile(dstFile, srcFile)

' update stats

count = count + 1

size = size + New FileInfo(srcFile).Length

sizeCompressed = sizeCompressed + New FileInfo(dstFile).Length

Next

' show stats

Dim msg As String = String.Format("Compressed {0} files in {1} ms." & vbCrLf & "Original size: {2:#,###}" & vbCrLf & "Compressed size: {3:#,###} ({4:0.00}% of original)", count, (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, size, sizeCompressed, (sizeCompressed / size) * 100.0)

label1.Text = msg

' now we can expand

btnExpand.Enabled = True

End Sub

The main line is marked in boldface. It calls the utility function CompressFile utility method to compress each selected file. The compressed files are stored in the \compressed directory under the application folder. They have the same name as the original file, plus a "cmp" extension.

Here’s the code for the CompressFile function:

Private Function CompressFile( dstFile As String, srcFile As String) As Boolean

' prepare to compress file

Dim retval As Boolean = True

Dim srcStream As FileStream = Nothing

Dim dstStream As FileStream = Nothing

Try

' open the files

srcStream = New FileStream(srcFile, FileMode.Open, FileAccess.Read)

dstStream = New FileStream(dstFile, FileMode.Create, FileAccess.Write)

' open compressor stream on destination file

Dim sw As C1ZStreamWriter = _

New C1ZStreamWriter(dstStream)

' copy source into compressor stream

StreamCopy(sw, srcStream)

Catch ' exception? tell caller we failed

retval = False

Finally ' always close our streams

If Not (srcStream Is Nothing) Then srcStream.Close()

If Not (dstStream Is Nothing) Then dstStream.Close()

End Try

' done

CompressFile = False

End Function

The function starts by creating two new file streams: one for the source file and one for the compressed file. Then it creates a C1ZStreamWriter object and attaches it to the destination stream. Next, it calls the StreamCopy function to transfer data from the source file and write it into the compressor stream.

Finally, the function closes both streams. Note the use of the Finally statement to ensure that both streams are properly closed even if there are exceptions while the function is executing.

The StreamCopy function simply copies bytes from one stream to another. Here’s the code:

Private Sub StreamCopy(dstStream As Stream, srcStream As Stream)

Dim buffer(32768) As Byte

Dim read As Integer

Do

read = srcStream.Read(buffer, 0, buffer.Length)

dstStream.Write(buffer, 0, read)

Loop While read > 0

dstStream.Flush()

End Sub

Note that the function calls the Flush method after it is done to ensure that any cached data is written out when the function is done copying. This is especially important when dealing with compressed streams, since they cache substantial amounts of data in order to achieve good compression rates.

Step 5: Add code to expand files.

Double-click the "Expand Files" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnExpand_Click(sender As Object, e As EventArgs) Handles btnExpand.Click

' get application directory

Dim appPath As String = Application.ExecutablePath

Dim i As Integer = appPath.IndexOf("\bin\")

If i > 0 Then appPath = appPath.Substring(0, i)

' create directory for expanded files

If Directory.Exists(appPath + DIR_EXP) Then

Directory.Delete(appPath + DIR_EXP, True)

End If

Directory.CreateDirectory(appPath + DIR_EXP)

' prepare to collect compression statistics

Dim count As Long

Dim size As Long

Dim sizeExpanded As Long

Dim ticks As Long = DateTime.Now.Ticks

' expand all files in "compressed" dir to "expanded" dir

Dim srcFile As String

Dim files As String()

files = Directory.GetFiles(appPath + DIR_COMP)

For Each srcFile In files

' expand file

Dim dstFile As String = _

appPath + DIR_EXP + "\" + Path.GetFileName(srcFile)

dstFile = dstFile.Replace(".cmp", "")

ExpandFile(dstFile, srcFile)

' update stats

count = count + 1

size = size + New FileInfo(srcFile).Length

sizeExpanded = sizeExpanded + New FileInfo(dstFile).Length

Next

' show stats

Dim msg As String

msg = String.Format(_

"Expanded {0} files in {1} ms." & vbCrLf & "Original size: {2:#,###}" & vbCrLf & "Expanded size: {3:#,###} ({4:0.00} x size of " & "compressed)", count, (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond, size, sizeExpanded, sizeExpanded / size)

label1.Text = msg

End Sub

The main line is marked in boldface. It calls the utility function ExpandFile utility method to expand the files that were compressed earlier. The expanded files are stored in the \expanded directory under the application folder. They have the same name as the original file, minus the "cmp" extension.

Here’s the code for the ExpandFile function:

Private Function ExpandFile(dstFile As String, srcFile As String) As Boolean

' prepare to expand file

Dim retval As Boolean = True

Dim srcStream As FileStream

Dim dstStream As FileStream

Try

' open the files

srcStream = New FileStream(srcFile, FileMode.Open, FileAccess.Read)

dstStream = New FileStream(dstFile, FileMode.Create, FileAccess.Write)

' open expander stream on compressed source

Dim sr As C1ZstreamReader = New C1ZStreamReader(srcStream)

' copy expander stream into destination file|

StreamCopy(dstStream, sr)

Catch ' exception? tell caller we failed

retval = False

Finally ' always close our streams

If Not (srcStream Is Nothing) Then srcStream.Close()

If Not (dstStream Is Nothing) Then dstStream.Close()

End Try

' done

ExpandFile = retval

End Sub

The function is similar to CompressFile, except it attaches a C1ZStreamReader to the source stream instead of attaching a C1ZStreamWriter to the destination stream.

This is the end of this tutorial.


Compressed Serialization

Compressed Serialization

This tutorial shows how you can serialize objects in compressed files, and then load them back into the memory.

The sample creates a data table using the NorthWind database. The table is saved (serialized) into regular and compressed streams. Finally, the data is loaded back from either stream.

Here is what the final application will look like:

Step 1: Create the main form.

Start a new Visual Basic project and add the following controls to the form:

1.

Four CommandButton controls along the left edge of the form, with the captions shown in the picture above. Set the Enabled property of the save and load buttons to false (they cannot be used until the data table has been created or saved).

2.

A DataGrid on the right of the form.

3.

A StatusBar docked at the bottom of the form.

Step 2: Add references and Imports statements.

Go to the Solution Explorer window, right-click on References, and select the "Add Reference…" menu option. Select the C1.C1Zip assembly from the list, or browse to find the C1.C1Zip.dll file.

Now double-click the form caption area to open the code window. At the top of the file, add the following statements:

Imports System.IO

Imports System.Data.OleDb

Imports System.Runtime.Serialization.Formatters.Binary

Imports C1.C1Zip

This declares the namespaces of the classes used in the project.

Step 3: Declare constants.

In the code window of the form, type or copy the following lines in the body of the form implementation.

Private Const FN_REGULAR = "\DataTable.regular"

Private Const FN_COMPRESSED = "\DataTable.compressed"

Private Const MDBFILE = "C:\Program Files\ComponentOne Studio.NET\common\NWIND.MDB"

These constants define the name of the database used to populate the data table and the file names used to serialize the data.

Step 4: Add code to create the data table.

Double-click the "Create Data Table" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnCreate_Click(sender As Object,e As EventArgs) Handles btnCreate.Click

' open table

Dim conn As String

conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & MDBFILE & ";"

Dim rs As String = "select * from customers"

' show status

Cursor = Cursors.WaitCursor

statusBar1.Text = "Loading data from mdb file..."

' load data

Dim da As OleDbDataAdapter = New OleDbDataAdapter(rs, conn)

Dim ds As DataSet = New DataSet()

Try

da.Fill(ds)

Catch

MessageBox.Show("Could not load data from " + MDBFILE)

End Try

' show status

Cursor = Cursors.Default

statusBar1.Text = "Loaded " & ds.Tables(0).Rows.Count & " records from mdb file."

' bind to grid

dataGrid1.DataSource = ds.Tables(0)

' enable save button

btnSave.Enabled = True

End Sub

The function uses standard ADO.NET objects and methods to create and populate a DataTable object, which is then bound to the DataGrid control.

Step 5: Add code to save the data table.

Double-click the "Save Data Table" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

' get data table from grid

Dim dt As DataTable = dataGrid1.DataSource

' show status

Cursor = Cursors.WaitCursor

statusBar1.Text = "Serializing data to regular file..."

' serialize the data set to a regular file

Dim fn As String = Application.StartupPath + FN_REGULAR

Dim fs As FileStream = New FileStream(fn, FileMode.Create)

Dim bf As BinaryFormatter = New BinaryFormatter()

bf.Serialize(fs, dt)

Dim lenRegular As Long = fs.Length

fs.Close()

' show status

Cursor = Cursors.WaitCursor

statusBar1.Text = "Serializing data to compressed file..."

' serialize the data set to a compressed file

fn = Application.StartupPath & FN_COMPRESSED

fs = New FileStream(fn, FileMode.Create)

Dim compressor As C1ZStreamWriter = New C1ZStreamWriter(fs)

bf = New BinaryFormatter()

bf.Serialize(compressor, dt)

Dim lenCompressed As Long = fs.Length

fs.Close()

' show status

Cursor = Cursors.Default

statusBar1.Text = string.Format( "Saved to regular file ({0:#,###} bytes) and " & "compressed file ({1:#,###} bytes)", lenRegular, lenCompressed)

' enable load buttons

btnLoad.Enabled = True

btnLoadCompressed.Enabled = True

End Sub

The main lines are the ones in boldface. The first set serializes the DataTable into a regular file; the second into a compressed file. Note that only one additional line is required to compress the data.

In both cases, the serialization is executed by the BinaryFormatter object. The only difference is that in the first case, the Serialize method is called with a regular file stream as a parameter; in the second, a C1ZStreamWriter is used instead.

Step 6: Add code to load the data table from the regular file.

Double-click the "Load Data Table" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click

' clear grid, show status

Cursor = Cursors.WaitCursor

dataGrid1.DataSource = Nothing

statusBar1.Text = "Loading from regular file..."

' deserialize from regular file

Dim fn As String = Application.StartupPath & FN_REGULAR

Dim fs As FileStream = New FileStream(fn, FileMode.Open)

Dim ticks As Long = DateTime.Now.Ticks

Dim bf As BinaryFormatter = New BinaryFormatter()

Dim dt As DataTable = bf.Deserialize(fs)

Dim ms As Long = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond

fs.Close()

' show result

Cursor = Cursors.Default

dataGrid1.DataSource = dt

statusBar1.Text = "Loaded from regular file in " & ms.ToString() & " ms."

End Sub

The main lines are in boldface. The first one creates a new BinaryFormatter object and the second one calls its Deserialize method. The Deserialize method takes a single parameter: the stream in which the object is defined. In this case, the stream is a regular file stream.

Step 7: Add code to load the data table from the compressed file.

Double-click the "Load Compressed Data Table" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnLoadCompressed_Click(sender As Object, e As EventArgs) Handles btnLoadCompressed.Click

' clear grid, show status

Cursor = Cursors.WaitCursor

dataGrid1.DataSource = Nothing

statusBar1.Text = "Loading from compressed file..."

' deserialize from compressed file

Dim fn As String = Application.StartupPath + FN_COMPRESSED

Dim fs As FileStream = New FileStream(fn, FileMode.Open)

Dim ticks As Long = DateTime.Now.Ticks

Dim decompressor As C1ZstreamReader

decompressor = New C1ZStreamReader(fs)

Dim bf As BinaryFormatter = New BinaryFormatter()

Dim dt As DataTable = bf.Deserialize(decompressor)

Dim ms As Long = (DateTime.Now.Ticks - ticks) / TimeSpan.TicksPerMillisecond

fs.Close()

' show result

Cursor = Cursors.Default

dataGrid1.DataSource = dt

statusBar1.Text = "Loaded from compressed file in " & ms.ToString() & " ms."

End Sub

The main lines are marked in boldface. They are similar to the code used to deserialize data from a regular file. The only difference is that instead of passing a regular file stream to the Deserialize method, we now use a C1ZStreamReader object.

This is the end of the Compressed Serialization Tutorial.


Handling Zip Files

Handling Zip Files

This tutorial shows how you can handle zip files, including:

1.

Opening an existing Zip file;

2.

Testing the integrity of a zip file,

3.

Expanding entries into memory streams,

4.

Adding entries to the zip file;

5.

Extracting entries from the zip file, and

6.

Removing entries from the zip file.

Here is what the final application will look like:

NOTE: This is a very simple application, designed to highlight the main functionality of the C1ZipFile object. The distribution disk also includes a more sophisticated version, written in C#, that supports more advanced features such as drag and drop, zipping folders, setting the compression level, etc.

Step 1: Create the main form.

Start a new Visual Basic project and add the following controls to the form:

1.

Six CommandButton controls along the left edge of the form, with the captions shown in the picture above.

2.

A ListView control covering the right part of the form. Click on the Columns property to bring up the column editor, then add columns to match those shown in the picture.

Step 2: Add a reference to the C1Zip assembly.

Go to the Solution Explorer window, right-click on References, and select the "Add Reference…" menu option. Select the C1.C1Zip assembly from the list, or browse to find the C1.C1Zip.dll file.

Now double-click the form caption area to open the code window. At the top of the file, add the following statements:

Imports System.IO

Imports C1. C1Zip

This makes the objects defined in the C1Zip and System.IO assemblies visible to the project.

Step 3: Declare a C1ZipFile object.

Switch to the code window and type (or copy) the following data member declaration:

Private m_Zip As C1ZipFile

This is the main object in this application. It implements the methods used to handle Zip files.

Step 4: Add code to initialize the C1ZipFile object.

Double-click the form caption area to add code to the Load event of the form. Type or copy the following code:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

' create C1ZipFile member

m_Zip = New C1ZipFile()

End Sub

This code creates a new C1ZipFile object and assigns it to the m_Zip member. Note that the C1ZipFile object cannot be used yet. It needs to be attached to an existing zip file first using the Open method (or to a new one using the Create method).

Step 5: Add code to open a Zip file.

Double-click the "Open Zip File…" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnOpen_Click(sender As Object, e As EventArgs) Handles btnOpen.Click

' show open file dialog

Dim fo As OpenFileDialog = New OpenFileDialog()

fo.FileName = "*.zip"

If fo.ShowDialog() <> DialogResult.OK Then Exit Sub

Try

m_Zip.Open(fo.FileName)

Catch

MessageBox.Show("Invalid ZIP file, please try again.")

End Try

' update display

UpdateDisplay()

End Sub

The main line is the one marked in boldface. It calls the Open method on the C1ZipFile object to attach the object to an existing zip file. Note the use of a Try/Catch statement, mainly to handle situations where the user selects a file that is not a zip file.

After opening the file, the code calls the UpdateDisplay utility function to display the contents of the zip file.

Step 6: Add code to update the display.

Next, add the UpdateDisplay utility function to display the contents of the zip file:

Private Sub UpdateDisplay()

' update ListView control to show Zip file contents

With ListView1

' remove any existing items

.Items.Clear()

' add each entry

Dim ze As C1ZipEntry

For Each ze In m_Zip.Entries

' calculate compression amount

Dim pct As Double = 0

If ze.SizeUncompressed > 0 Then

pct = 1 - ze.SizeCompressed / ze.SizeUncompressed

End If

' build listview item

Dim items(4) As String

items(0) = ze.FileName

items(1) = Format(ze.Date, "MM/dd/yy")

items(2) = Format(ze.SizeUncompressed, "#,##0")

items(3) = Format(ze.SizeCompressed, "#,##0")

items(4) = Format(pct, "00 %")

Dim lvi As ListViewItem = New ListViewItem(items)

' save ZipEntry into item tag

lvi.Tag = ze

' add item to listview

.Items.Add(lvi)

Next

' update UI

Dim hasEntries As Boolean = (.Items.Count > 0)

btnExtract.Enabled = hasEntries

btnRemove.Enabled = hasEntries

btnTest.Enabled = hasEntries

End With

End Sub

The main lines are marked in boldface. They start by declaring a C1ZipEntry object and using it in a ForEach loop over the entries in the zip file (m_Zip.Entries).

For each entry, the function creates a ListViewItem containing the information extracted from the C1ZipEntry object and adds the new entry to the ListView control. Note that the C1ZipEntry object itself is also saved in the Tag property of the ListView items.

Finally, the code enables or disables the command buttons depending on whether or not there are entries available to be extracted, removed or tested.

Step 7: Add code to test the integrity the Zip file.

Double-click the "Test Zip File" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click

' test each entry

Dim ze As C1ZipEntry

For Each ze In m_Zip.Entries

If Not ze.CheckCRC32() Then

MessageBox.Show("** Entry " + ze.FileName + " has errors.", "C1Zip", MessageBoxButtons.OK, MessageBoxIcon.Error)

Exit Sub

End If

Next

' if we got here, everything is OK

MessageBox.Show("All entries passed CRC check", "C1Zip")

End Sub

The main lines are marked in boldface. They declare a C1ZipEntry variable and use it to loop over the entries in the zip file. The routine then calls the CheckCRC32 method on each entry to check whether the actual checksum of the bytes stored in the file matches the checksum stored in the entry header. The function returns true if the values match and false if they don't (which indicates the entry is corrupted).

Step 8: Add code to view the contents of an entry.

Double-click the "View File” command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnView_Click(sender As Object, e As EventArgs) Handles btnView.Click

' get first selected item that is not a directory

Dim ze As C1ZipEntry

Dim lvi As ListViewItem

For Each lvi In ListView1.SelectedItems

Dim zeItem As C1ZipEntry = lvi.Tag

If (zeItem.Attributes And _

FileAttributes.Directory) = 0 Then

ze = zeItem

Exit For

End If

Next

' make sure we got something

If ze Is Nothing Then

MessageBox.Show("Sorry, no files to show...", "C1Zip")

Exit Sub

End If

' read entry content into a string

Dim entry As Stream = ze.OpenReader()

Dim sr As StreamReader = New StreamReader(entry)

Dim entryText As String = sr.ReadToEnd()

entry.Close()

' make sure entry is not too big for MessageBox

If entryText.Length > 16000 Then

entryText = entryText.Substring(0, 16000)

End If

' show entry in message box

MessageBox.Show(entryText, ze.FileName)

End Sub

The function starts by choosing the first selected zip entry that is not a subdirectory. If a valid entry cannot be found, the function exits.

The function then calls the OpenReader method to obtain a Stream that can be used to read the contents of the entry. There are no temporary files or additional delays involved in this step, the data is expanded as it is read from the stream.

Next, the function reads the entry content directly into a string using the ReadToEnd method on the StreamReader object, then closes the stream.

Finally, the string is truncated and displayed in a MessageBox.

Note that this function was designed to show the contents of short text files. If you try to view the contents of binary files, it will show only a couple of characters.

Step 9: Add code to add entries to the Zip file.

Double-click the "Add Files…" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click

' get list of files to add

Dim fo As OpenFileDialog = New OpenFileDialog()

fo.Multiselect = True

fo.FileName = "*.*"

If fo.ShowDialog <> DialogResult.OK Then Exit Sub

' add files in the list

Dim file As String

For Each file In fo.FileNames()

m_Zip.Entries.Add(file)

Next

' done

UpdateDisplay()

End Sub

Adding new entries to a Zip file is easy. The line in boldface simply calls the Add method on the C1ZipFile object, passing a string that contains the full name of the file to be added. That’s all there is to it.

Step 10: Add code to extract a Zip entry.

Double-click the "Extract Files” command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnExtract_Click(sender As Object, e As EventArgs) Handles btnExtract.Click

' make sure we have some selected entries

Dim cnt As Integer = ListView1.SelectedIndices.Count

If cnt = 0 Then

MessageBox.Show("Sorry, no files to extract...", "C1Zip")

Exit Sub

End If

' confirm with user

Dim dr As DialogResult

Dim msg As String

msg = "Please confirm that you want to extract " + cnt.ToString() + " entries."

dr = MessageBox.Show(msg, "C1Zip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)

If dr <> DialogResult.OK Then Exit Sub

' extract all selected entries

Dim lvi As ListViewItem

Dim ze As C1ZipEntry

For Each lvi In ListView1.SelectedItems

ze = lvi.Tag

If ze.SizeCompressed > 0 Then

m_Zip.Entries.Extract(ze.FileName)

End If

Next

' done

UpdateDisplay()

End Sub

The most important line is marked in boldface. It calls the Extract method on the Entries property of the C1ZipFile object. The parameter is the string that contains the file name of the entry (which is stored in the entry’s FileName property).

By default, the Extract method expands the entry and saves it in the same directory where the zip file is located. There are other versions of this method that allow you to specify the destination directory and file name for the expanded file. For more details, see the C1.C1Zip Reference section.

Step 11: Add code to remove entries from the Zip file.

Double-click the "Remove Files" command button to open the code window, then type (or copy) the following code to handle the click event:

Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click

' make sure we have some selected entries

Dim cnt As Integer = ListView1.SelectedIndices.Count

If cnt = 0 Then

MessageBox.Show("Oops, no files to remove...", "C1Zip")

Exit Sub

End If

' confirm with user

Dim dr As DialogResult

Dim msg As String

msg = "Please confirm that you want to delete " + cnt.ToString() + " entries."

dr = MessageBox.Show(msg, "C1Zip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)

If dr <> DialogResult.OK Then Exit Sub

' delete all selected entries

Dim lvi As ListViewItem

Dim ze As C1ZipEntry

For Each lvi In ListView1.SelectedItems

ze = lvi.Tag

m_Zip.Entries.Remove(ze.FileName)

Next

' done

UpdateDisplay()

End Sub

The most important line is marked in boldface. It calls the Remove method on the Entries property of the C1ZipFile object. The parameter is the string that contains the file name of the entry (which is stored in the entry’s FileName property).

This is the end of this tutorial.


C1.C1Zip Reference

C1.C1Zip Reference

C1ZipFile class

C1ZipEntryCollection class

C1ZipEntry class

C1ZStreamWriter class

C1ZStreamReader class

Enumerations


C1ZipFile class

C1ZipFile class

Used for creating, opening, and managing zip files.

C1ZipFile Members

C1ZipFile Constructor

C1ZipFile Properties

C1ZipFile Methods

C1ZipFile Events


C1ZipFile Members

C1ZipFile Members

C1ZipFile Public Properties

Comment Supported by the .NET Compact Framework. | Gets or sets a comment string associated with the zip file that is currently open.
CompressionLevel Supported by the .NET Compact Framework. | Gets or sets the amount of compression applied to files being zipped.
Entries Supported by the .NET Compact Framework. | Gets a collection of entries in the zip file that is currently open.
FileName Supported by the .NET Compact Framework. | Gets the name of the zip file that is currently open.
OverwriteReadOnly Supported by the .NET Compact Framework. | Overwrite read-only files when extracting files. The default is false.
Password Supported by the .NET Compact Framework. | Password to use when adding or retrieving entries from the zip file.

C1ZipFile Public Instance Methods

Close Supported by the .NET Compact Framework. | Closes the zip file that is currently open and clears the Entries collection.
Create Supported by the .NET Compact Framework. | Creates a new empty zip file with the given name. If a file with this name exists, it is overwritten.
IsZipFile Supported by the .NET Compact Framework. | Determines whether a file contains a Zip directory.
Open Supported by the .NET Compact Framework. | Opens an existing zip file.
Refresh Supported by the .NET Compact Framework. | Refreshes the Entries collection with information for the currently open zip file.
StreamCopy Supported by the .NET Compact Framework. | Utility method for copying bytes from one stream to another.

C1ZipFile Public Events

Progress
Supported by the .NET Compact Framework.

Fires while C1ZipFile is compressing an entry into the zip file. The event allows you to update UI elements such as progress bars, or cancel the operation if the user decides to do so.


C1ZipFile Constructor

C1ZipFile Constructor

Syntax

[VB]

Public Sub New()

[C#]

public C1ZipFile()

[Delphi]

constructor C1ZipFile.Create;


C1ZipFile Properties

C1ZipFile Properties

Comment Property (C1ZipFile)

CompressionLevel Property

Entries Property

FileName Property (C1ZipFile)

OverwriteReadOnly Property

Password Property


Comment Property (C1ZipFile)

Comment Property (C1ZipFile)

Previous Next

Gets or sets a comment string associated with the zip file that is currently open.

Syntax

[VB]

Public Property Comment As String

[C#]

public string Comment { get; set; }

[Delphi]

property Comment: string;

See Also

C1ZipFile class


CompressionLevel Property

CompressionLevel Property

Gets or sets the amount of compression applied to files being zipped.

Syntax

[VB]

Public Property CompressionLevel As CompressionLevelEnum

[C#]

public CompressionLevelEnum CompressionLevel { get; set; }

[Delphi]

property CompressionLevel: CompressionLevelEnum;

Remarks

Valid settings for the CompressionLevel property are:

Member Name | Description
BestCompression | Minimizes the file size of the compressed file.
BestSpeed | Minimizes compression time.
DefaultCompression | Normal compression time and speed.
NoCompression | There is no compression.

See Also

C1ZipFile class

CompressionLevelEnum Enumeration


Entries Property

Entries Property

Gets a collection of entries in the zip file that is currently open.

Syntax

[VB]

Public Property Entries As C1ZipEntryCollection

[C#]

public C1ZipEntryCollection Entries { get; }

[Delphi]

property Entries: C1ZipEntryCollection;

See Also

C1ZipFile class


FileName Property (C1ZipFile)

FileName Property (C1ZipFile)

Previous Next

Gets the name of the zip file that is currently open.

Syntax

[VB]

Public Property FileName As String

[C#]

public string FileName { get; }

[Delphi]

property FileName: string;

See Also

C1ZipFile class


OverwriteReadOnly Property

OverwriteReadOnly Property

Overwrites read-only files when extracting files.

Syntax

[VB]

Public Property OverwriteReadOnly As Boolean

[C#]

public bool OverwriteReadOnly { get; set;}

[Delphi]

property OverwriteReadOnly: Boolean;

Remarks

The default value of this property is False.

See Also

C1ZipFile class


Password Property

Password Property

Gets or sets the password to be used for compressing or extracting entries from the current zip file.

Syntax

[VB]

Public Property Password As String

[C#]

public string Password { get; set; }

[Delphi]

property Password: string;

Remarks

If the Password property is set to a non-empty string, any entries added to the zip file will be encrypted and protected by the password. To extract these entries later, the same password must be used.

For example, the following code creates a zip file with three entries. The first one is not protected, the other two use passwords "first" and "second":

Imports C1.C1Zip

…

Dim zip As C1ZipFile = New C1ZipFile()

zip.CompressionLevel = CompressionLevelEnum.BestCompression

zip.Create("c:\temp\test.zip")

zip.Entries.Add("c:\file1.bmp")

zip.Password = "first"

zip.Entries.Add("c:\file2.bmp")

zip.Password = "second"

zip.Entries.Add("c:\file1.bmp")

zip.Password = ""

You can check whether entries are encrypted using the IsEncrypted property. For example:

Dim ze As C1ZipEntry

For Each ze In zip.Entries

If ze.IsEncrypted Then

Debug.WriteLine(ze.FileName + " (encrypted)")

Else

Debug.WriteLine(ze.FileName)

End If

Next

Of course, you can't retrieve the password from the file. If you decide to protect the entries in your zip files with a password and forget or lose the password, you will not be able to retrieve the files later.

See Also

C1ZipFile class


C1ZipFile Methods

C1ZipFile Methods

Close Method

Create Method

IsZipFile Method

Open Method

Refresh Method

StreamCopy Method


Close Method

Close Method

Closes the zip file that is currently open and clear the Entries collection.

Syntax

[VB]

Public Sub Close()

[C#]

public void Close()

[Delphi]

procedure Close;

Remarks

You don't have to call this method, C1ZipFile always closes the underlying zip file after each operation. The Close method simply clear the FileName property and the Entries collection.

See Also

C1ZipFile class


Create Method

Create Method

Creates a new empty zip file with the given name. If a file with this name exists, it is overwritten.

Syntax

[VB]

Public Sub Create(ByVal fn As String)

[C#]

public void Create(string fileName)

[Delphi]

procedure Create(fileName: string);

See Also

C1ZipFile class


IsZipFile Method

IsZipFile Method

Determines whether a file contains a Zip directory.

Syntax

[VB]

Public Shared Function IsZipFile(ByVal fileName As String) As Boolean

[C#]

public static bool IsZipFile(string fileName)

[Delphi]

function IsZipFile(fileName: string): Boolean;

See Also

C1ZipFile class


Open Method

Open Method

Opens an existing zip file.

Syntax

[VB]

Public Sub Open(ByVal fn As String)

[C#]

public void Open(string fileName)

[Delphi]

procedure Open(fileName: string);

See Also

C1ZipFile class


Refresh Method

Refresh Method

Refreshes the Entries collection with information for the currently open zip file.

Syntax

[VB]

Public Sub Refresh()

[C#]

public void Refresh()

[Delphi]

procedure Refresh;

Remarks

This method is useful in case a separate application changes the zip file that is currently open.

See Also

C1ZipFile class


StreamCopy Method

StreamCopy Method

Utility method for copying bytes from one stream to another.

Syntax

public static void StreamCopy(Stream dstStream, Stream srcStream, int bytesToCopy)

See Also

C1ZipFile class


C1ZipFile Events

C1ZipFile Events


Progress Event

Progress Event

Fires while C1ZipFile is compressing an entry into the zip file. The event allows you to update UI elements such as progress bars, or cancel the operation if the user decides to do so.

Syntax

[VB]

Public Event Progress(ByVal sender As Object, ByVal e As ZipProgressEventArgs) As ZipProgressEventHandler

[C#]

public event ZipProgressEventHandler Progress;

[Delphi]

property Progress: ZipProgressEventHandler;

Event Data

The event handler receives an argument of type ZipProgressEventArgs containing data related to this event. The following properties provide information specific to this event:

Argument | Description
string FileName | The name of the file being added to the zip file.
int FileLength | The length (in bytes) of the file being added to the zip file.
int Position | The position within the file being compressed (between zero and FileLength).
bool Cancel | Set to True in order to cancel the operation.

See Also

C1ZipFile class


C1ZipEntryCollection class

C1ZipEntryCollection class

Contains a collection of entries present in a zip file (C1ZipFile object).

C1ZipEntryCollection Members

C1ZipEntry Indexers

C1ZipEntryCollection Properties

C1ZipEntryCollection Methods


C1ZipEntryCollection Members

C1ZipEntryCollection Members

C1ZipEntryCollection Public Properties

Count
Supported by the .NET Compact Framework.

Gets the number of entries in the Entries collection.

C1ZipEntryCollection Public Instance Methods

Add Supported by the .NET Compact Framework. | Adds a file to the zip file.
Extract Supported by the .NET Compact Framework. | Extracts a file from the zip file based on its name or index.
OpenWriter Supported by the .NET Compact Framework. | Returns a Stream object that can be used to write data directly into the zip file without saving it to a disk file first.
Remove Supported by the .NET Compact Framework. | Removes a file from the zip file based on its index or name.


C1ZipEntry Indexers

C1ZipEntry Indexers

Gets an entry based on its index in the Entries collection.

Syntax

public C1ZipEntry this [int index] { get; }

public C1ZipEntry this [string name] { get; }

Remarks

Gets an entry based on its filename. If a full match is found, the corresponding entry is returned. If a full match is not found, partial matches are sought. Partial matches include the full file name but exclude the path stored in the zip file.


C1ZipEntryCollection Properties

C1ZipEntryCollection Properties


Count Property

Count Property

Gets the number of entries in the Entries collection.

Syntax

[VB]

Public Property Count As Integer

[C#]

public int Count { get; }

[Delphi]

property Count: Integer;

See Also

C1ZipEntryCollection class


C1ZipEntryCollection Methods

C1ZipEntryCollection Methods

Add Method

Extract Method

OpenWriter Method

Remove Method


Add Method

Add Method

Adds a file to the zip file.

Syntax, overload 1

[VB]

Public Sub Add(ByVal fileNames As String( ))

[C#]

public void Add(string fileNames)

[Delphi]

procedure Add(fileNames: string);

Remarks

Adds a file to the zip file. If the zip file already contains a file with the same name, the old entry is removed before the new one is added. The file name stored excludes any path information. For example, if you add "c:\winnt\system32\myfile.ocx" to the zip file, the file name stored in the zip file will be "myfile.ocx".

Syntax, overload 2

[VB]

Public Sub Add(ByVal fileName As String, ByVal pathLevels As Integer)

[C#]

public void Add(string fileName, int pathLevels)

[Delphi]

procedure Add(fileName: string; pathLevels: Integer);

Remarks

Adds a file to the zip file. The file name stored will include the specified number of directory levels. For example, if you add "c:\winnt\system32\myfile.ocx" to the zip file, with pathLevels set to two, the file name stored in the zip file will be "winnt\system32\myfile.ocx".

Syntax, overload 3

[VB]

Public Sub Add(ByVal fileName As String, ByVal entryName As String)

[C#]

public void Add(string fileName, string entryName)

[Delphi]

procedure Add(fileName: string; entryName: string);

Remarks

Adds files to a zip archive and specify the path to be stored in the archive. For example, the code below stores all files in the "c:\" directory into a zip file as "mydir\myfiles\*.*":

foreach (string fileName in Directory.GetFiles(@"c:\"))

{

try

{

string fileTitle = Path.GetFileName(fileName);

_zipFile.Entries.Add(fname, @"mydir\myfiles\" + fileTitle);

}

catch {}

}

Note that the Add(string fileName) method stores the specified file into the zip archive, but trims the path name. The new method Add(string fileName, string entryName) allows you to store the full path name. For example:

string fileName = @"c:\myfiles\myletters\joe.txt";

_zip.Entries.Add(fileName); // << stores entry as 'joe.txt'

_zip.Entries.Add(fileName, fileName); // << stores entry as

'c:\myfiles\myletters\joe.txt'

Syntax, overload 4

[VB]

Public Sub Add(ByVal stream As Stream, ByVal entryName As String)

[C#]

public void Add(Stream stream, string entryName)

[Delphi]

procedure Add(stream: Stream; entryName: string);

Remarks

Compresses a stream and adds it to the zip file. If the zip file already contains an entry with the same name, the old entry is removed before the new one is added.

See Also

C1ZipEntryCollection class


Extract Method

Extract Method

Extracts a file from the zip file based on its name or index.

Syntax, overload 1

[VB]

Public Sub Extract(ByVal index As Integer)

Public Sub Extract(ByVal sourceFileName As String)

[C#]

public void Extract(int index)

public void Extract(string sourcefileName)

[Delphi]

procedure Extract(index: integer);

procedure Extract(sourceFileName: string);

Remarks

The file is created with the name stored in the zip file, in the directory that contains the zip file.

Syntax, overload 2

[VB]

Public Sub Extract(ByVal index As Integer, ByVal destFileName As String)

Public Sub Extract(ByVal sourceFileName As String, ByVal destFileName As String)

[C#]

public void Extract(int index, string dstFileName)

public void Extract(string srcFileName, string dstFileName)

[Delphi]

procedure Extract(index: integer; destFileName: string);

procedure Extract(sourceFileName: string; destFileName: string);

Remarks

Extracts a file from the zip file based on its name or index. The file is created with the specified name and location.

See Also

C1ZipEntryCollection class


OpenWriter Method

OpenWriter Method

Returns a Stream object that can be used to write data directly into the zip file without saving it to a disk file first.

Syntax

[VB]

Public Function OpenWriter(ByVal streamName As String, ByVal memory As Boolean) As Stream

[C#]

public Stream OpenWriter(string entryName, bool memory)

[Delphi]

function OpenWriter(streamName: string; memory: Boolean): Stream;

Remarks

The data is cached until you close the stream, at which point it is written to the file. This reduces the risk of corrupting the zip file in case there's any errors while the data is being written to the stream. The memory parameter determines whether the data is cached in memory or in a temporary file.

See Also

C1ZipEntryCollection class


Remove Method

Remove Method

Removes a file from the zip file based on its index or name.

Syntax, overload 1

[VB]

Public Sub Remove(ByVal index As Integer)

Public Sub Remove(ByVal fileName As String)

[C#]

public void Remove(int index)

public void Remove(string fileName)

[Delphi]

procedure Remove(index: integer);

procedure Remove(fileName: string);

Remarks

Removes a file from the zip file based on its index or name. If a full match is found, the corresponding entry is returned. If a full match is not found, partial matches are sought. Partial matches include the full file name but exclude the path stored in the zip file.

Syntax, overload 2

[VB]

Public Sub Remove(ByVal indices As Integer( ))

[C#]

public void Remove(int[] indices)

[Delphi]

procedure Remove(indices: Integer);

Remarks

Removes several files from the zip file. This is much more efficient than removing the files individually, because none of the files being removed need to be moved within the zip file.

Syntax, overload 3

[VB]

Public Sub Remove(ByVal fileNames As String( ))

[C#]

public void Remove(string[] fileNames)

[Delphi]

procedure Remove(fileNames: string);

Remarks

Removes several files from the zip file. This is much more efficient than removing the files individually, because none of the files being removed need to be moved within the zip file.

See Also

C1ZipEntryCollection class


C1ZipEntry class

C1ZipEntry class

Represents an individual entry present in a zip file (C1ZipFile object).


C1ZipEntry Members

C1ZipEntry Members

C1ZipEntry Public Properties

Attributes Supported by the .NET Compact Framework. | Gets the file attributes (e.g., archive, directory, read-only, system, hidden, etc.).
Comment Supported by the .NET Compact Framework. | Gets or sets a comment string associated with the entry.
CRC32 Supported by the .NET Compact Framework. | Gets the CRC32 code calculated when the file was compressed.
Date Supported by the .NET Compact Framework. | Gets the data of the last modification made to the original file.
FileName Supported by the .NET Compact Framework. | Gets the name of the compressed file.
IsEncrypted Supported by the .NET Compact Framework. | Gets a value that indicates whether a password is needed to extract the entry from the zip file.
SizeCompressed Supported by the .NET Compact Framework. | Gets the compressed size of the file.
SizeUncompressed Supported by the .NET Compact Framework. | Gets the original size of the file.

C1ZipEntry Public Instance Methods

CheckCRC32 Supported by the .NET Compact Framework. | Calculates the CRC32 code for the entry and compares it with the CRC32 value stored with the entry.
OpenReader Supported by the .NET Compact Framework. | Returns a Stream object that can be used to read the data stored in the entry without extracting it to a disk file.


C1ZipEntry Properties

C1ZipEntry Properties

Attributes Property

Comment Property (C1ZipEntry)

CRC32 Property

Date Property

FileName Property (C1ZipEntry)

IsEncrypted Property

SizeCompressed Property (C1ZipEntry)

SizeUncompressed Property (C1ZipEntry)


Attributes Property

Attributes Property

Gets the file attributes (e.g., archive, directory, read-only, system, hidden, etc.).

Syntax

[VB]

Public Property Attributes As FileAttributes

[C#]

public FileAttributes Attributes { get; }

[Delphi]

property Attributes: FileAttributes;

See Also

C1ZipEntry class


Comment Property (C1ZipEntry)

Comment Property (C1ZipEntry)

Previous Next

Gets or sets a comment string associated with the entry.

Syntax

[VB]

Public Property Comment As String

[C#]

public string Comment { get; set; }

[Delphi]

property Comment: string;

See Also

C1ZipEntry class


CRC32 Property

CRC32 Property

Gets the CRC32 code calculated when the file was compressed.

Syntax

[VB]

Public Property CRC32 As Integer

[C#]

public int CRC32 { get; }

[Delphi]

property CRC32: Integer;

Remarks

This value is useful for checking the integrity of the compressed entries.

See Also

C1ZipEntry class


Date Property

Date Property

Gets the data of the last modification made to the original file.

Syntax

[VB]

Public Property Date As DateTime

[C#]

public DateTime Date { get; }

[Delphi]

property Date: DateTime;

See Also

C1ZipEntry class


FileName Property (C1ZipEntry)

FileName Property (C1ZipEntry)

Previous Next

Gets the name of the compressed file.

Syntax

[VB]

Public Property FileName As String

[C#]

public string FileName { get; }

[Delphi]

property FileName: string;

See Also

C1ZipEntry class


IsEncrypted Property

IsEncrypted Property

Gets a value that indicates whether a password is needed to extract the entry from the zip file.

Syntax

[VB]

Public Property IsEncrypted As Boolean

[C#]

public bool IsEncrypted { get; }

[Delphi]

property IsEncrypted: Boolean;

Remarks

For more details on how to use encryption and passwords, see the Password property.

See Also

C1ZipEntry class


SizeCompressed Property (C1ZipEntry)

SizeCompressed Property (C1ZipEntry)

Previous Next

Gets the compressed size of the file.

Syntax

[VB]

Public Property SizeCompressed As Integer

[C#]

public int SizeCompressed { get; }

[Delphi]

property SizeCompressed: Integer;

See Also

C1ZipEntry class


SizeUncompressed Property (C1ZipEntry)

SizeUncompressed Property (C1ZipEntry)

Previous Next

Gets the original size of the file.

Syntax

[VB]

Public Property SizeUncompressed As Integer

[C#]

public int SizeUncompressed { get; }

[Delphi]

property SizeUncompressed: Integer;

See Also

C1ZipEntry class


C1ZipEntry Methods

C1ZipEntry Methods


CheckCRC32 Method

CheckCRC32 Method

Calculates the CRC32 code for the entry and compares it with the CRC32 value stored with the entry.

Syntax

[VB]

Public Function CheckCRC32() As Boolean

[C#]

public bool CheckCRC32()

[Delphi]

function CheckCR32: Boolean;

Remarks

Returns true if the values are the same.

See Also

C1ZipEntry class


OpenReader Method

OpenReader Method

Returns a Stream object that can be used to read the data stored in the entry without extracting it to a disk file.

Syntax

[VB]

Public Function OpenReader() As Stream

[C#]

public Stream OpenReader()

[Delphi]

function OpenReader: Stream;

Remarks

The data is decompressed as it is read from the file. The Length and Position properties of the returned stream object reflect compressed bytes. You must close the returned stream when you're done reading from it.

See Also

C1ZipEntry class


C1ZStreamWriter class

C1ZStreamWriter class

Compresses output as it is written to a regular output stream. This class is a wrapper around a ZLib.ZStream object.

The C1ZStreamWriter acts a filter between an application and a base stream. The base stream handles the data store, and can be any type of writable stream, including memory buffers, disk files, or network streams.


C1ZStreamWriter Members

C1ZStreamWriter Members

C1ZStreamWriter Public Properties

BaseStream Supported by the .NET Compact Framework. | Gets the underlying stream responsible for writing the compressed data.
Checksum Supported by the .NET Compact Framework. | Gets the checksum calculated as the stream is written.
OwnsBaseStream Supported by the .NET Compact Framework. | Determines whether the C1ZStreamWriter object owns the base stream.
SizeCompressed Supported by the .NET Compact Framework. | Gets the number of compressed bytes written into the underlying stream.
SizeUncompressed Supported by the .NET Compact Framework. | Gets the number of uncompressed bytes sent to the stream.
ZStream Supported by the .NET Compact Framework. | Gets the underlying ZStream object responsible for compressing the data.


C1ZStreamWriter Constructors

C1ZStreamWriter Constructors

Syntax

[VB]

Public Sub New(ByVal baseStream As System.IO.Stream)

Public Sub New(ByVal baseStream As System.IO.Stream, ByVal zip As Boolean)

Public Sub New(ByVal baseStream As System.IO.Stream, ByVal header As Boolean, ByVal crc32 As Boolean)

Public Sub New(ByVal baseStream As System.IO.Stream, ByVal level As C1.C1Zip.CompressionLevelEnum)

Public Sub New(ByVal baseStream As System.IO.Stream, ByVal level As C1.C1Zip.CompressionLevelEnum, ByVal zip As Boolean)

Public Sub New(ByVal baseStream As System.IO.Stream, ByVal level As C1.C1Zip.CompressionLevelEnum, ByVal header As Boolean, ByVal crc32 As Boolean)

[C#]

public C1ZStreamWriter(Stream baseStream)

public C1ZStreamWriter(Stream baseStream, bool zip)

public C1ZStreamWriter(Stream baseStream, bool header, bool crc32)

public C1ZStreamWriter(Stream baseStream, CompressionLevelEnum level)

public C1ZStreamWriter(Stream baseStream, CompressionLevelEnum level, bool zip)

public C1ZStreamWriter(Stream baseStream, CompressionLevelEnum level, bool header, bool crc32)

[Delphi]

constructor C1ZStreamWriter.Create(baseStream: Stream);

constructor C1ZStreamWriter.Create(baseStream: Stream; zip: boolean);

constructor C1ZStreamWriter.Create(baseStream: Stream; header: boolean; crc32: boolean);

constructor C1ZStreamWriter.Create(baseStream: Stream; level: CompressionLevelEnum);

constructor C1ZStreamWriter.Create(baseStream: Stream; level: CompressionLevelEnum; zip: boolean);

constructor C1ZStreamWriter.Create(baseStream: Stream; level: CompressionLevelEnum; header: boolean; crc32: boolean);

Remarks

The baseStream parameter is an output stream that will store the compressed data.

The level parameter specifies the compression level. Higher compression takes longer to write. The default value provides a nice balance between compression level and speed.

The zip parameter specifies whether the compressed stream should be compatible with zip files. Streams in zip files are different from regular zlib streams in two aspects: (1) zip streams do not contain any local header information (the information is stored in the zip file headers instead) and (2) zip streams use a CRC32 checksum instead of the adler32 checksum used by zlib streams.

The header and crc32 parameters specify whether the stream will contain a local header and the type of checksum to be used.

By default, header is set to true and crc32 is set to false.


C1ZStreamWriter Properties

C1ZStreamWriter Properties

BaseStream Property (C1ZStreamWriter)

Checksum Property

OwnsBaseStream Property (C1ZStreamWriter)

SizeCompressed Property (C1ZStreamWriter)

SizeUncompressed Property (C1ZStreamWriter)

ZStream Property (C1ZStreamWriter)


BaseStream Property (C1ZStreamWriter)

BaseStream Property (C1ZStreamWriter)

Previous Next

Gets the underlying stream responsible for writing the compressed data.

Syntax

[VB]

Public Property BaseStream As Stream

[C#]

public Stream BaseStream { get; }

[Delphi]

property BaseStream: Stream;

See Also

C1ZStreamWriter class


Checksum Property

Checksum Property

Gets the checksum calculated as the stream is written.

Syntax

[VB]

Public Property Checksum As Integer

[C#]

public int Checksum { get;}

[Delphi]

property Checksum: Integer;

Remarks

The checksum may be a crc32 or an adler32 checksum, depending on how the stream was created.

See Also

C1ZStreamWriter class


OwnsBaseStream Property (C1ZStreamWriter)

OwnsBaseStream Property (C1ZStreamWriter)

Previous Next

Determines whether the C1ZStreamWriter object owns the base stream.

Syntax

[VB]

Public Property OwnsBaseStream As Boolean

[C#]

public bool OwnsBaseStream { get; set; }

[Delphi]

property OwnsBaseStream: Boolean;

Remarks

If this property is set to true, closing the C1ZStreamWriter will also close the base stream. By default, this property is false, so the base stream remains open after the C1ZStreamWriter object is closed.

See Also

C1ZStreamWriter class


SizeCompressed Property (C1ZStreamWriter)

SizeCompressed Property (C1ZStreamWriter)

Previous Next

Gets the number of compressed bytes written into the underlying stream.

Syntax

[VB]

Public Property SizeCompressed As Integer

[C#]

public int SizeCompressed { get; }

[Delphi]

property SizeCompressed: Integer;

See Also

C1ZStreamWriter class


SizeUncompressed Property (C1ZStreamWriter)

SizeUncompressed Property (C1ZStreamWriter)

Previous Next

Gets the number of uncompressed bytes sent to the stream.

Syntax

[VB]

Public Property SizeUncompressed As Integer

[C#]

public int SizeUncompressed { get; }

[Delphi]

property SizeUncompressed: Integer;

See Also

C1ZStreamWriter class


ZStream Property (C1ZStreamWriter)

ZStream Property (C1ZStreamWriter)

Previous Next

Gets the underlying ZStream object responsible for compressing the data.

Syntax

[VB]

Public Property ZStream As ZStream

[C#]

public ZStream ZStream { get; }

[Delphi]

property ZStream: ZStream;

See Also

C1ZStreamWriter class


C1ZStreamReader class

C1ZStreamReader class

Expands input as it is read from a compressed input stream. This class is a wrapper around a ZLib.ZStream object.

The C1ZStreamReader acts as a filter between a base stream and an application. The base stream handles the data store, and can be any type of readable stream, including memory buffers, disk files, or network streams.

Note that the C1ZStreamReader object does not own the base stream, so closing the C1ZStreamReader object does not close the base stream.


C1ZStreamReader Members

C1ZStreamReader Members

C1ZStreamReader Public Properties

BaseStream Supported by the .NET Compact Framework. | Gets the underlying stream responsible for providing the compressed data that is decompressed as it is read.
Checksum Supported by the .NET Compact Framework. | Gets the checksum calculated as the stream is written.
OwnsBaseStream Supported by the .NET Compact Framework. | Determines whether the C1ZStreamReader object owns the base stream.
SizeCompressed Supported by the .NET Compact Framework. | Gets the number of compressed bytes read from the underlying stream.
SizeUncompressed Supported by the .NET Compact Framework. | Gets the number of uncompressed bytes provided by the decompressor.
ZStream Supported by the .NET Compact Framework. | Gets the underlying ZStream object responsible for decompressing the data.


C1ZStreamReader Constructors

C1ZStreamReader Constructors

Syntax

[VB]

Public Sub New(ByVal baseStream As Stream)

Public Sub New(ByVal baseStream As Stream, ByVal zip As Boolean)

Public Sub New(ByVal baseStream As Stream, ByVal header As Boolean, ByVal crc32 As Boolean)

Public Sub New(ByVal baseStream As Stream, ByVal zip As Boolean, ByVal sizeCompressed As Integer)

Public Sub New(ByVal baseStream As Stream, ByVal zip As Boolean, ByVal sizeCompressed As Integer, ByVal method As Integer)

[C#]

public C1ZStreamReader(Stream baseStream)

public C1ZStreamReader(Stream baseStream, bool zip)

public C1ZStreamReader(Stream baseStream, bool header, bool crc32)

public C1ZStreamReader (Stream baseStream , bool zip , Int32 sizeCompressed )

public C1ZStreamReader ( System.IO.Stream baseStream , System.Boolean zip , System.Int32 sizeCompressed , System.Int32 method )

[Delphi]

constructor C1ZStreamReader.Create(baseStream: Stream);

constructor C1ZStreamReader.Create(baseStream: Stream; zip: boolean);

constructor C1ZStreamReader.Create(baseStream: Stream; header: boolean; crc32: boolean);

constructor C1ZStreamReader.Create(baseStream: Stream; zip: boolean; sizeCompressed: integer);

constructor C1ZStreamReader.Create(baseStream: Stream; zip: boolean; sizeCompressed: integer; method: integer);

Remarks

The baseStream parameter is a compressed input stream (usually created with a C1ZStreamWriter object) that will be decompressed as it is read.

The zip parameter specifies whether the compressed stream is compatible with zip files. Streams in zip files are different from regular zlib streams in two aspects: (1) zip streams do not contain any local header information (the information is stored in the zip file headers instead) and (2) zip streams use a CRC32 checksum instead of the adler32 checksum used by zlib streams.


C1ZStreamReader Properties

C1ZStreamReader Properties

BaseStream Property (C1ZStreamReader)

OwnsBaseStream Property (C1ZStreamReader)

SizeCompressed Property (C1ZStreamReader)

SizeUncompressed Property (C1ZStreamReader)

ZStream Property (C1ZStreamReader)


BaseStream Property (C1ZStreamReader)

BaseStream Property (C1ZStreamReader)

Previous Next

Gets the underlying stream responsible for providing the compressed data that is decompressed as it is read.

Syntax

[VB]

Public Property BaseStream As Stream

[C#]

public Stream BaseStream { get; }

[Delphi]

property BaseStream: Stream;

See Also

C1ZStreamReader class


OwnsBaseStream Property (C1ZStreamReader)

OwnsBaseStream Property (C1ZStreamReader)

Previous Next

Determines whether the C1ZStreamReader object owns the base stream.

Syntax

[VB]

Public Property OwnsBaseStream As Boolean

[C#]

public bool OwnsBaseStream { get; set; }

[Delphi]

property OwnsBaseStream: Boolean;

Remarks

If this property is set to True, closing the C1ZStreamReader will also close the base stream. By default, this property is false, so the base stream remains open after the C1ZStreamReader object is closed.

See Also

C1ZStreamReader class


SizeCompressed Property (C1ZStreamReader)

SizeCompressed Property (C1ZStreamReader)

Previous Next

Gets the number of compressed bytes read from the underlying stream.

Syntax

[VB]

Public Property SizeCompressed As Integer

[C#]

public int SizeCompressed { get; }

[Delphi]

property SizeCompressed: Integer;

See Also

C1ZStreamReader class


SizeUncompressed Property (C1ZStreamReader)

SizeUncompressed Property (C1ZStreamReader)

Previous Next

Gets the number of uncompressed bytes provided by the decompressor.

Syntax

[VB]

Public Property SizeUncompressed As Integer

[C#]

public int SizeUncompressed { get; }

[Delphi]

property SizeUncompressed: Integer;

See Also

C1ZStreamReader class


ZStream Property (C1ZStreamReader)

ZStream Property (C1ZStreamReader)

Previous Next

Gets the underlying ZStream object responsible for decompressing the data.

Syntax

[VB]

Public Property ZStream As ZStream

[C#]

public ZStream ZStream { get; }

[Delphi]

property ZStream: ZStream;

See Also

C1ZStreamReader class


Enumerations

Enumerations


CompressionLevelEnum Enumeration

CompressionLevelEnum Enumeration

Determines whether a file is compressed and at what speed or amount.

Syntax

[VB]

Public enum CompressionLevelEnum

[C#]

public enum CompressionLevelEnum

[Delphi]

type CompressionLevelEnum = (BestCompression, BestSpeed, DefaultCompression, NoCompression);

Remarks

Use the members of this enumeration to set the value of the CompressionLevel property.

Member Name | Description
BestCompression | Minimizes the file size of the compressed file.
BestSpeed | Minimizes compression time.
DefaultCompression | Normal compression time and speed.
NoCompression | There is no compression.

See Also

CompressionLevel Property


C1.C1Zip.ZLib Reference

C1.C1Zip.ZLib Reference

This namespace contains a C# implementation of the ZLIB library, which handles the actual data compression and decompression for all classes in C1.C1Zip.

ZLIB was written by Jean-loup Gailly and Mark Adler. It is an open-source library. For more information on ZLIB, check http://www.info-zip.org/ or http://www.gzip.org/.

ZLIB is designed to be a free, general-purpose, legally unencumbered -- that is, not covered by any patents – loss-less data-compression library for use on virtually any computer hardware and operating system. The ZLIB data format is itself portable across platforms. Unlike the LZW compression method used in Unix compress and in the GIF image format, the compression method used in ZLIB essentially never expands the data. (LZW can double or triple the file size in extreme cases.) ZLIB's memory footprint is also independent of the input data.


ZStream class

ZStream class

ZStream is the most flexible (and hardest to use) class in the C1.C1Zip assembly. It contains a C# implementation of ZLIB's zstream object, which is a general purpose compressor and decompressor.

In most cases, you should be able to use the C1ZStreamReader and C1ZStreamWriter classes instead of ZStream. These classes provide friendly and easy-to-use wrappers that handle ZLIB details for you.

Use ZStream only if you are familiar with ZLIB and need control over the low-level aspects of the data compression or decompression process (e.g., to provide your own buffers or compression dictionaries). If you use ZStream directly and need technical support, please check out the detailed documentation, sample, and articles available at http://www.info-zip.org/ or http://www.gzip.org/.

ZStream Members

ZStream Constructors

ZStream Properties

ZStream Methods


ZStream Members

ZStream Members

ZStream Public Properties

avail_in Supported by the .NET Compact Framework. | Number of bytes available in the input buffer.
avail_out Supported by the .NET Compact Framework. | Number of bytes available in the output buffer.
next_in Supported by the .NET Compact Framework. | Input buffer.
next_in_index Supported by the .NET Compact Framework. | Position of cursor in input buffer.
next_out Supported by the .NET Compact Framework. | Output buffer.
next_out_index Supported by the .NET Compact Framework. | Position of cursor in output buffer.
total_in Supported by the .NET Compact Framework. | Total number of input bytes read so far.
total_out Supported by the .NET Compact Framework. | Total number of bytes output so far.

ZStream Public Instance Methods

deflate Supported by the .NET Compact Framework. | deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.
deflateEnd Supported by the .NET Compact Framework. | All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.
deflateInit Supported by the .NET Compact Framework. | Initializes the internal stream state for compression.
deflateParams Supported by the .NET Compact Framework. | Dynamically update the compression level and compression strategy.
deflateSetDictionary Supported by the .NET Compact Framework. | Initializes the compression dictionary from the given byte sequence without producing any compressed output.
inflate Supported by the .NET Compact Framework. | inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may some introduce some output latency (reading input without producing any output) except when forced to flush.
inflateEnd Supported by the .NET Compact Framework. | All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.
inflateInit Supported by the .NET Compact Framework. | Initializes the internal stream state for decompression.
inflateSetDictionary Supported by the .NET Compact Framework. | Initializes the decompression dictionary from the given uncompressed byte sequence.
inflateSync Supported by the .NET Compact Framework. | Skips invalid compressed data until a full flush point (see the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided.


ZStream Constructors

ZStream Constructors

Syntax

[VB]

Public Sub New()

Public Sub New(ByVal crc32 As Boolean)

[C#]

public ZStream()

public ZStream(bool crc32)

[Delphi]

constructor ZStream.Create;

constructor ZStream.Create(crc32: boolean);

The crc32 parameter determines the type of checksum to use when writing compressed streams. If crc32 is set to true, ZStream uses a CRC32 checksum (the same used in zip files). If crc32 is set to false (the default value), ZStream uses a slightly faster adler32 checksum that is compatible with the standard ZLIB implementation.


ZStream Properties

ZStream Properties

avail_in Property

avail_out Property

next_in Property

next_in_index Property

next_out Property

next_out_index Property

total_in Property

total_out Property


avail_in Property

avail_in Property

Number of bytes available in the input buffer.

Syntax

[VB]

Public Dim avail_in As Integer

[C#]

public int avail_in;

[Delphi]

property avail_in: Integer;

See Also

ZStream class


avail_out Property

avail_out Property

Number of bytes available in the output buffer.

Syntax

[VB]

Public Dim avail_out As Integer

[C#]

public int avail_out;

[Delphi]

property avail_out: Integer;

See Also

ZStream class


next_in Property

next_in Property

Input buffer.

Syntax

[VB]

Public Dim next_in As Byte

[C#]

public byte[] next_in;

[Delphi]

property next_in: Byte;

See Also

ZStream class


next_in_index Property

next_in_index Property

Position of cursor in input buffer.

Syntax

[VB]

Public Dim next_in_index As Integer

[C#]

public int next_in_index;

[Delphi]

property next_in_index: Integer;

See Also

ZStream class


next_out Property

next_out Property

Output buffer.

Syntax

[VB]

Public Dim next_out As Byte

[C#]

public byte[] next_out;

[Delphi]

property next_out: Byte;

See Also

ZStream class


next_out_index Property

next_out_index Property

Position of cursor in output buffer.

Syntax

[VB]

Public Dim next_out_index As Integer

[C#]

public int next_out_index;

[Delphi]

property next_out_index: Integer;

See Also

ZStream class


total_in Property

total_in Property

Total number of input bytes read so far.

Syntax

[VB]

Public Dim total_in As Long

[C#]

public long total_in;

[Delphi]

property total_in: Long;

See Also

ZStream class


total_out Property

total_out Property

Total number of bytes output so far.

Syntax

[VB]

Public Dim total_out As Long

[C#]

public long total_out;

[Delphi]

property total_out: Long;

See Also

ZStream class


ZStream Methods

ZStream Methods

deflate Method

deflateEnd Method

deflateInit Method

deflateParams Method

deflateSetDictionary Method

inflate Method

inflateEnd Method

inflateInit Method

inflateSetDictionary Method

inflateSync Method


deflate Method

deflate Method

deflate compresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.

Syntax

[VB]

Public Function deflate(ByVal flush As Integer) As Integer

[C#]

public int deflate(int flush)

[Delphi]

function deflate(flush: Integer): Integer;

Remarks

The detailed semantics are as follows. deflate performs one or both of the following actions:

1.

Compress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in and avail_in are updated and processing will resume at this point for the next call to deflate.

2.

Provide more output starting at next_out and update next_out and avail_out accordingly. This action is forced if the parameter flush is non zero. Forcing flush frequently degrades the compression ratio, so this parameter should be set only when necessary (in interactive applications). Some output may be provided even if flush is not set.

Before the call to deflate, the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating avail_in or avail_out accordingly; avail_out should never be zero before the call. The application can consume the compressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of deflate. If deflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending.

If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for some compression algorithms and so it should be used only when necessary.

If flush is set to Z_FULL_FLUSH, all output is flushed as with Z_SYNC_FLUSH, and the compression state is reset so that decompression can restart from this point if previous compressed data has been damaged or if random access is desired. Using Z_FULL_FLUSH too often can seriously degrade the compression.

If deflate returns with avail_out == 0, this function must be called again with the same value of the flush parameter and more output space (updated avail_out), until the flush is complete (deflate returns with non-zero avail_out).

If the parameter flush is set to Z_FINISH, pending input is processed, pending output is flushed and deflate returns with Z_STREAM_END if there was enough output space; if deflate returns Z_OK, this function must be called again with Z_FINISH and more output space (updated avail_out) but no more input data, until it returns with Z_STREAM_END or an error. After deflate has returned Z_STREAM_END, the only possible operations on the stream are deflateReset or deflateEnd.

Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least 0.1% larger than avail_in plus 12 bytes. If deflate does not return Z_STREAM_END, then it must be called again as described above.

deflate returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if all input has been consumed and all output has been produced (only when flush is set to Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example if next_in or next_out was null), Z_BUF_ERROR if no progress is possible (for example avail_in or avail_out was zero).

See Also

ZStream class


deflateEnd Method

deflateEnd Method

All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.

Syntax

[VB]

Public Function deflateEnd() As Integer

[C#]

public int deflateEnd()

[Delphi]

function deflateEnd: Integer;

Remarks

deflateEnd returns Z_OK on success, Z_STREAM_ERROR if the stream state was inconsistent, Z_DATA_ERROR if the stream was freed prematurely (some input or output was discarded).

See Also

ZStream class


deflateInit Method

deflateInit Method

Initializes the internal stream state for compression.

Syntax

[VB]

Public Function deflateInit(ByVal level As Integer) As Integer

Public Function deflateInit(ByVal level As Integer, ByVal bits As Integer) As Integer

[C#]

public int deflateInit(int level)

public int deflateInit(int level, int bits)

[Delphi]

function deflateInit(level: integer): Integer;

function deflateInit(level: integer; bits: integer): Integer;

Remarks

The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION requests a default compromise between speed and compression (equivalent to level 6).

deflateInit returns Z_OK if successful, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if level is not a valid compression level, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller.

deflateInit does not perform any compression: this is done by the deflate method.

See Also

ZStream class


deflateParams Method

deflateParams Method

Dynamically update the compression level and compression strategy.

Syntax

[VB]

Public Function deflateParams(ByVal level As Integer, ByVal strategy As Integer) As Integer

[C#]

public int deflateParams(int level, int strategy)

[Delphi]

function deflateParams(level: Integer; strategy: Integer): Integer;

Remarks

The interpretation of level and strategy is as in deflateInit2. This can be used to switch between compression and straight copy of the input data, or to switch to a different kind of input data requiring a different strategy. If the compression level is changed, the input available so far is compressed with the old level (and may be flushed); the new level will take effect only at the next call to deflate.

Before the call to deflateParams, the stream state must be set as for a call of deflate, since the currently available input may have to be compressed and flushed. In particular, avail_out must be non-zero.

deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if avail_out was zero.

See Also

ZStream class


deflateSetDictionary Method

deflateSetDictionary Method

Initializes the compression dictionary from the given byte sequence without producing any compressed output.

Syntax

[VB]

Public Function deflateSetDictionary(ByVal dictionary As Byte( ), ByVal dictLength As Integer) As Integer

[C#]

public int deflateSetDictionary(byte[] dictionary, int dictLength)

[Delphi]

function deflateSetDictionary(dictionary: Byte; dictLength: Integer): Integer;

Remarks

This function must be called immediately after deflateInit, deflateInit2 or deflateReset, before any call to deflate. The compressor and decompressor must use exactly the same dictionary (see the inflateSetDictionary Method).

The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.

Depending on the size of the compression data structures selected by deflateInit, a part of the dictionary may in effect be discarded, for example if the dictionary is larger than the window size in deflate. Thus the strings most likely to be useful should be put at the end of the dictionary, not at the front.

deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (such as NULL dictionary) or the stream state is inconsistent (for example if deflate has already been called for this stream). deflateSetDictionary does not perform any compression: this is done by deflate.

See Also

ZStream class


inflate Method

inflate Method

inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush.

Syntax

[VB]

Public Function inflate(ByVal f As Integer) As Integer

[C#]

public int inflate(int f)

[Delphi]

function inflate(f: Integer): Integer;

Remarks

The detailed semantics are as follows. inflate performs one or both of the following actions:

1.

Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), next_in is updated and processing will resume at this point for the next call to inflate.

2.

Provide more output starting at next_out and update next_out and avail_out accordingly. inflate provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter).

Before the call to inflate, the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate. If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending.

If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much output as possible to the output buffer. The flushing behavior of inflate is not specified for values of the flush parameter other than Z_SYNC_FLUSH and Z_FINISH, but the current implementation actually flushes as much output as possible anyway.

inflate should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call to inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all the uncompressed data. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The next operation on this stream must be inflateEnd to deallocate the decompression state. The use of Z_FINISH is never required, but can be used to inform inflate that a faster routine may be used for the single inflate call.

inflate returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect checksum), Z_STREAM_ERROR if the stream structure was inconsistent (for example if next_in or next_out was null), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress is possible or if there was not enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR case, the application may then call inflateSync to look for a good compression block.

See Also

ZStream class


inflateEnd Method

inflateEnd Method

All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output.

Syntax

[VB]

Public Function inflateEnd() As Integer

[C#]

public int inflateEnd()

[Delphi]

function inflateEnd: Integer;

Remarks

inflateEnd returns Z_OK on success, Z_STREAM_ERROR if the stream state was inconsistent.

See Also

ZStream class


inflateInit Method

inflateInit Method

Initializes the internal stream state for decompression.

Syntax

[VB]

Public Function inflateInit() As Integer

Public Function inflateInit(ByVal bits As Integer) As Integer

[C#]

public int inflateInit()

public int inflateInit(int bits)

[Delphi]

function inflateInit: Integer;

function inflateInit(bits: Integer): Integer;

Remarks

The fields next_in and avail_in must be initialized before by the caller. If next_in is not null and avail_in is large enough (the exact value depends on the compression method), inflateInit determines the compression method from the zlib header and allocates all data structures accordingly; otherwise the allocation will be deferred to the first call to inflate.

inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller.

inflateInit does not perform any decompression apart from reading the zlib header if present: this is done by inflate. (So next_in and avail_in may be modified, but next_out and avail_out are unchanged.)

See Also

ZStream class


inflateSetDictionary Method

inflateSetDictionary Method

Initializes the decompression dictionary from the given uncompressed byte sequence.

Syntax

[VB]

Public Function inflateSetDictionary(ByVal dictionary As Byte( ), ByVal dictLength As Integer) As Integer

[C#]

public int inflateSetDictionary(byte[] dictionary, int dictLength)

[Delphi]

function inflateSetDictionary(dictionary: Byte; dictLength: Integer): Integer;

Remarks

This function must be called immediately after a call of inflate if this call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the Adler32 value returned by this call to inflate. The compressor and decompressor must use exactly the same dictionary (see the deflateSetDictionary Method).

inflateSetDictionary returns Z_OK on success, Z_STREAM_ERROR if a parameter is invalid (such as NULL dictionary) or the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect Adler32 value). inflateSetDictionary does not perform any decompression: this is done by subsequent calls to inflate.

See Also

ZStream class


inflateSync Method

inflateSync Method

Skips invalid compressed data until a full flush point (see the description of the deflate Method with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided.

Syntax

[VB]

Public Function inflateSync() As Integer

[C#]

public int inflateSync()

[Delphi]

function inflateSync: Integer;

Remarks

inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the success case, the application may save the current value of total_in which indicates where valid compressed data was found. In the error case, the application may repeatedly call inflateSync, providing more input each time, until success or end of the input data.

See Also

ZStream class