Introduction
Recently, a requirement had come to me wherein I had to copy some files to a given destination at runtime. So the best thing that came to my mind was to use the Resource (RESX) file for storing the zipped file, and at runtime extracting it and putting it into the destination path.
I used SharpZipLib for extracting zip files.
Using the Code
Before beginning, you need to add a reference to SharpZipLib.dll.
Following were the steps followed to achieve the requirement:
Step 1: Right click on Project in Solution Explorer and add a Resource file.
Step 2: Add the ZIP file into the Resource file.
Next use the following code to extract the zip:
using System.Text;
using System.IO;
using System.Resources;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
using System.Resources;
using System.Reflection;
private void ExtractFiles()
{
try
{
ResourceManager objResMgr = new ResourceManager
("namespace.resource_filename", Assembly.GetExecutingAssembly());
byte[] objData = (byte[])objResMgr.GetObject("zipfilename");
MemoryStream objMS = new MemoryStream(objData);
ZipInputStream objZIP = new ZipInputStream(objMS);
ZipEntry theEntry;
while ((theEntry = objZIP.GetNextEntry()) != null)
{
FileStream streamWriter =
File.Create(Path.Combine("destination path", theEntry.Name));
int size = objData.Length;
byte[] data = new byte[size];
while (true)
{
size = objZIP.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
objZIP.Close();
}
catch (MissingManifestResourceException ex)
{
}
catch (Exception e1)
{
}
}
Just be careful with the namespace.resourcefilename
and zip file name that you add to the Resource file in the following:
ResourceManager objResMgr = new ResourceManager
("namespace.resource_filename", Assembly.GetExecutingAssembly());
byte[] objData = (byte[])objResMgr.GetObject("zipfilename");
History
- 29th August, 2007: Initial post