Tuesday, February 8, 2011

UNZIP a zip file through C#

Hi,
We had a FTP location where our vendors place a ZIP file. The idea is to process file once it is placed through a listner application. So we need to unzip the placed file through an application. The API: ICSharpCode.SharpZipLib.Zip was very much helpful to achieve the same.

Sample source code is below:

using System;
using System.Collections.Generic;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;

namespace unzipper
{
class Program
{
static void Main(string[] args)
{
UnZipFiles("C:\\TEST\\SharpZipLib_0860_Bin.zip", "C:\\TEST\\", "", false);
}

public static void UnZipFiles(string zipPathAndFile, string outputFolder, string password, bool deleteZipFile)
{
ZipInputStream s = new ZipInputStream(File.OpenRead(zipPathAndFile));
if (password != null && password != String.Empty)
s.Password = password;
ZipEntry theEntry;
string tmpEntry = String.Empty;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = outputFolder;
string fileName = Path.GetFileName(theEntry.Name);
// create directory
if (directoryName != "")
{
Directory.CreateDirectory(directoryName);
}
if (fileName != String.Empty)
{
if (theEntry.Name.IndexOf(".ini") < fullpath =" directoryName" fullpath =" fullPath.Replace(" fulldirpath =" Path.GetDirectoryName(fullPath);" streamwriter =" File.Create(fullPath);" size =" 2048;" data =" new" size =" s.Read(data,"> 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
}
s.Close();
if (deleteZipFile)
File.Delete(zipPathAndFile);
}
}
}

Hope it Helpz...
Reference: http://www.eggheadcafe.com/tutorials/aspnet/9ce6c242-c14c-4969-9251-af95e4cf320f/zip--unzip-folders-and-files-with-c.aspx
Regards
Fauzi

No comments: