Introduction
This article shall describe an approach that may be used to collect files from multiple locations and zip them up into a single zipped folder. The code contained in the sample project may be useful if one needs to gather up multiple files, zip them up and then do something with them such as upload the zipped files to a server location for storage or processing. The application uses the SharpZipLib
for the basis of the compression function.
Figure 1: Demo User Interface for Folder Compression Project
As was mentioned, the example code is dependent upon the SharpZipLib
libraries; these libraries may be downloaded from this location: The Zip, GZip, BZip2 and Tar Implementation For .NET. In addition to handling ZIP files, the library also handles TAR, GZIP and BZIP2 compression.
The Solution
The solution contains a single project. The example is provided in the form of a single Windows Forms project that contains a single main form (frmMain
). The references are all in the default configuration, with the exception being that the SharpZipLib
DLL has been added (first item in the reference list). Having downloaded the DLL from the Open Source Projects for the .NET Platform web, the download was installed into the local file system and was adding using the "Add Reference" dialog’s Browse option. All of the code necessary to drive the application is included in the main form’s code file.
Figure 2: The Solution Explorer Showing the Project
The Code: Compress Folders – Main Form
The Compress Folders project is a Windows Forms project containing a single form. All UI and code required by the project are contained in the single main form (frmMain.cs). The only references added to the project, aside from the defaults, were those necessary to support the use of the SharpZipLib in the project. The imports, namespace and class declarations are as follows:
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.ComponentModel;
using System.Windows.Forms;
using System.Management;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
namespace CompressFolders
{
public partial class frmMain : Form
{
After the class declaration, the next block of code is the default constructor and empty form load event handler:
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
The next block of code is used to handle the Browse button’s click event. This button is used to display the open file dialog, which is used to capture the path to a folder that the user wants to include in the zipped folder. The code is annotated such that you may review descriptions of what each section of the code is doing by reading though this code block:
private void btnBrowse_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Add File";
openFileDialog1.Filter = "All Files (*.*)|*.*";
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
string sFilePath;
sFilePath = openFileDialog1.FileName;
if (sFilePath == "")
return;
if (System.IO.File.Exists(sFilePath) == false)
return;
else
txtAddFile.Text = sFilePath;
}
The next block of code is used to add a file selected by the previous method (Browse button) and add to a list of files to include in the zipped folder. Again, this section of code is annotated to describe what each part of the code does.
private void btnAddFile_Click(object sender, EventArgs e)
{
if (txtAddFile.Text == string.Empty)
{
MessageBox.Show("Use the browse button to search for " +
"the file to be added.", "Missing File Name");
return;
}
for (int i = 0; i < lstFilePaths.Items.Count; i++)
{
if (lstFilePaths.Items[i].ToString() ==
txtAddFile.Text.ToString())
{
MessageBox.Show("That file has already been added to the
list.", "Duplicate");
return;
}
}
if (txtAddFile.Text != string.Empty)
lstFilePaths.Items.Add(txtAddFile.Text.ToString());
txtAddFile.Text = string.Empty;
txtAddFile.Focus();
}
The next section of code is the Remove button’s click event handler. This method allows the user to remove items from the listbox list after they have been added using the Browse button and Add button.
private void btnRemoveFile_Click(object sender, EventArgs e)
{
try
{
lstFilePaths.Items.Remove(lstFilePaths.SelectedItem);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
Next up is a button event handler that uses the Folder Browser Dialog control to help the user specify a destination path for the finished ZIP file.
private void btnSaveBrowse_Click(object sender, EventArgs e)
{
txtSaveTo.Text = string.Empty;
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtSaveTo.Text = folderBrowserDialog1.SelectedPath;
}
}
The next button click event handler contains the code used to gather up the marked files and zip them up the destination folder set. The code will gather up the identified files, copy the files to a temporary folder inside the destination folder, zip them up and then remove the temporary folder. This code is also annotated and you may review the notes contained within the code block to read a description of what is happening at each stage in the progress.
private void btnSave_Click(object sender, EventArgs e)
{
if (lstFilePaths.Items.Count < 1)
{
MessageBox.Show("There are not files queued for the zip
operation", "Empty File Set");
return;
}
if (txtSaveTo.Text == string.Empty)
{
MessageBox.Show("No destination file has been defined.",
"Save To Empty");
return;
}
lblUpdate.Visible = true;
lblUpdate.Refresh();
string[] sTemp = txtSaveTo.Text.Split('\\');
string sZipFileName = sTemp[sTemp.Length - 1].ToString();
FileInfo fi = new FileInfo(txtSaveTo.Text + '\\' + sZipFileName +".zip");
if (fi.Exists)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("The file " + sZipFileName + " already exists.
");
sb.Append("You may rename it in the save to text box.");
MessageBox.Show(sb.ToString(), "Existing File Name");
txtSaveTo.Focus();
return;
}
catch
{
MessageBox.Show("Rename the file or select a new
location.", "File Error");
return;
}
}
if (!System.IO.Directory.Exists(txtSaveTo.Text +
"\\TempZipFile\\"))
{
System.IO.Directory.CreateDirectory(txtSaveTo.Text +
"\\TempZipFile\\");
}
string sTargetFolderPath = (txtSaveTo.Text + "\\TempZipFile\\");
for (int i = 0; i < lstFilePaths.Items.Count; i++)
{
string filePath = lstFilePaths.Items[i].ToString();
FileInfo fi2 = new FileInfo(filePath);
if (fi2.Exists)
{
try
{
fi2.CopyTo(sTargetFolderPath + fi2.Name, true);
}
catch
{
System.IO.Directory.Delete(sTargetFolderPath);
MessageBox.Show("Could not copy files to temp
folder.", "File Error");
return;
}
}
}
try
{
lblUpdate.Visible = true;
lblUpdate.Refresh();
string[] filenames = Directory.GetFiles(sTargetFolderPath);
using (ZipOutputStream s = new
ZipOutputStream(File.Create(txtSaveTo.Text + "\\" +
sZipFileName + ".zip")))
{
s.SetLevel(9);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0,
buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
s.Finish();
s.Close();
}
lblUpdate.Visible = false;
System.IO.Directory.Delete(txtSaveTo.Text +
"\\TempZipFile\\", true);
MessageBox.Show("Zip file " + txtSaveTo.Text + " created.");
lstFilePaths.Items.Clear();
txtSaveTo.Text = string.Empty;
txtAddFile.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Zip Operation
Error");
}
}
The only remaining code in the project is that which is used to terminate the application.
private void btnExit_Click(object sender, EventArgs e)
{
this.Dispose();
}
}
}
That wraps up the description of the code used in this project.
Summary
This example demonstrates zipping up a folder using SharpZipLib. In this example, the interface is provided in the form of a stand-alone desktop application. The same approach described in this project could be applied within the context of a large application that may be required to gather up multiple files and zip them into a single zipped folder. As with all things, there are other ways to do this same sort of thing. However, given the availability of the SharpZipLib, this is a relatively simple process.