Sometimes in an application you need to unzip the folder and read the contents out of that folder. For unzipping purpose you can use the FREE SharpZipLib Library. Check out the code below which is used to unzip the zip folder and place the unzipped folder in the Files directory of the application.
First, the Button_Upload is used to send the zip file to the Server's Folder.
protected void Btn_Upload_Click(object sender, EventArgs e)
{
string folder = Server.MapPath("~/Files/");
string filePath = FileUpload1.PostedFile.FileName;
string fileName = System.IO.Path.GetFileName(filePath);
FileUpload1.PostedFile.SaveAs(folder + fileName);
// Unzip the file
UnzipFile(filePath, folder);
}
After the folder has been transfered to the folder you can use the following code to unzip it.
private
void UnzipFile(string zipFilePath, string folder) {
ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
string serverFolder = Server.MapPath("~/Files/");
// create directory
Directory.CreateDirectory(serverFolder +directoryName);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(( serverFolder + theEntry.Name));
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
}
You can download the SharpZipLib Library from the following link:
http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx