How to Zip Folders & Subfolders in .Net
Zipping files in .NET C# is used to package a group of files and send them in an email. It also makes the file available for administrators to view. Creating zip files is accomplished using the .NET J# libraries. These libraries are clones of the popular Java compiler. Once the libraries are imported, a few lines of code zips folders and files into one zip package.
Instructions
-
-
1
Import the Java libraries. There are three libraries that need to be declared at the beginning of the code file. Below is the list with the appropriate syntax:
using java.util;
using java.util.zip;
using java.io; -
2
Instantiate the zip file classes. Below, two variables are assigned. ZipFile is used to create the zip file used for packaging. ZipStream is used to add files to the package.
FileOutputStream zipFile = new FileOutputStream("C:\\myZipFile.zip");
ZipOutputStream zipStream= new ZipOutputStream(zipFile ); -
-
3
Assign a directory to a variable and add it to the zip entries. The following code grabs a file within a directory and adds it to the zip file. The file is not written to the zip package at this point. Actual placement of the file occurs in the following step:
ZipEntry myZipPlacement = new ZipEntry(Path.GetFileName("C:\\myDirectory\\myFile.txt"));
zipStream.putNextEntry(myZipPlacement);
myFillFile = new FileInputStream("C:\\myDirectory\\myFile.txt"); -
4
Write the file to the zip package. The file is written byte-by-byte using a file buffer variable. The following code writes the file that was setup as an entry in Step 3:
sbyte[] myBuffer = new sbyte[1024];
int i= 0;
while ((i=myFillFile.read(myBuffer)) >= 0)
{
zipStream.write(myBuffer, 0, i);
} -
5
Close the stream. This code is necessary to free memory resource on the server and release the "read" lock from the zip file:
zipStream.closeEntry();
myFillFile.close();
myZipPlacement.close();
zipFile.close();
-
1