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 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 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:
/// <summary>
/// Select files for subsequent addition to the list of
/// files to be archived
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnBrowse_Click(object sender, EventArgs e)
{
// configure the open file dialog
openFileDialog1.Title = "Add File";
openFileDialog1.Filter = "All Files (*.*)|*.*";
openFileDialog1.FileName = "";
// return if the user cancels the operation
if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return;
}
// set a local variable to contain the file name
// captured from the open file dialog
string sFilePath;
sFilePath = openFileDialog1.FileName;
if (sFilePath == "")
return;
// make sure the file exists before adding
// its path to the list of files to be
// compressed
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 included in the zipped folder. Again, this section of code is annotated to describe what each part of the code does.
/// <summary>
/// Button click event handler used to add files from the browse
/// textbox to the listbox control
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAddFile_Click(object sender, EventArgs e)
{
// Check for content in the text box
if (txtAddFile.Text == string.Empty)
{
MessageBox.Show("Use the browse button to search for " +
"the file to be added.", "Missing File Name");
return;
}
// Only allow the file to be added if the file is not a duplicate
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;
}
}
// Add the file to the listbox list
if (txtAddFile.Text != string.Empty)
lstFilePaths.Items.Add(txtAddFile.Text.ToString());
// clear the textbox and move the focus back to the textbox
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.
/// <summary>
/// Button click handler to remove selected items from
/// the listbox
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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.
/// <summary>
/// Button click handler used to set the path to
/// the zipped file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSaveBrowse_Click(object sender, EventArgs e)
{
// clear the folder path
txtSaveTo.Text = string.Empty;
// Show the FolderBrowserDialog.
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.
/// <summary>
/// Collect the files into a common folder location, zip the
/// files up, and delete the copied files and folder
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSave_Click(object sender, EventArgs e)
{
// make sure there are files to zip
if (lstFilePaths.Items.Count < 1)
{
MessageBox.Show("There are not files queued for the zip
operation", "Empty File Set");
return;
}
// make sure there is a destination defined
if (txtSaveTo.Text == string.Empty)
{
MessageBox.Show("No destination file has been defined.",
"Save To Empty");
return;
}
lblUpdate.Visible = true;
lblUpdate.Refresh();
// name the zip file whatever the folder is named
// by splitting the file path to get the folder name
string[] sTemp = txtSaveTo.Text.Split('\\');
string sZipFileName = sTemp[sTemp.Length - 1].ToString();
// check to see if zipped file already exists
// user may rename it in the text box if it does.
FileInfo fi = new FileInfo(txtSaveTo.Text + '\\' + sZipFileName +".zip");
if (fi.Exists)
{
// move it to the folder
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;
}
}
// Check for the existence of the target folder and
// create it if it does not exist
if (!System.IO.Directory.Exists(txtSaveTo.Text +
"\\TempZipFile\\"))
{
System.IO.Directory.CreateDirectory(txtSaveTo.Text +
"\\TempZipFile\\");
}
// Set up a string to hold the path to the temp folder
string sTargetFolderPath = (txtSaveTo.Text + "\\TempZipFile\\");
// Process the files and move each into the target folder
for (int i = 0; i < lstFilePaths.Items.Count; i++)
{
string filePath = lstFilePaths.Items[i].ToString();
FileInfo fi2 = new FileInfo(filePath);
if (fi2.Exists)
{
// move it to the folder
try
{
fi2.CopyTo(sTargetFolderPath + fi2.Name, true);
}
catch
{
// clean up if the operation failed
System.IO.Directory.Delete(sTargetFolderPath);
MessageBox.Show("Could not copy files to temp
folder.", "File Error");
return;
}
}
}
// zip up the files
try
{
lblUpdate.Visible = true;
lblUpdate.Refresh();
string[] filenames = Directory.GetFiles(sTargetFolderPath);
// Zip up the files - From SharpZipLib Demo Code
using (ZipOutputStream s = new
ZipOutputStream(File.Create(txtSaveTo.Text + "\\" +
sZipFileName + ".zip")))
{
s.SetLevel(9); // 0-9, 9 being the highest compression
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();
}
// remove the progress bar
lblUpdate.Visible = false;
// clean up files by deleting the temp folder and its content
System.IO.Directory.Delete(txtSaveTo.Text +
"\\TempZipFile\\", true);
// Notify user
MessageBox.Show("Zip file " + txtSaveTo.Text + " created.");
// empty everything
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.
/// <summary>
/// Exit the application
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnExit_Click(object sender, EventArgs e)
{
this.Dispose();
}
}
}
That wraps up the description of the code used in this project.
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.
转载:http://www.codeproject.com/KB/files/sharpziplib.aspx