I want to compress a directory(folder) that includes multi files to (.zip) file in Asp.net 2 that runs in IIS 6 and i can not upgrade my .net version because i forced to run my project in IIS 6.
after i searched in google, i faced with below code. unfortunately this code is wrong and result of this code has wrong format.
public void CompressFile(string sDir, string sRelativePath, GZipStream zipStream)
{
//Compress file name
char[] chars = sRelativePath.ToCharArray();
zipStream.Write(BitConverter.GetBytes(chars.Length), 0, sizeof(int));
foreach (char c in chars)
zipStream.Write(BitConverter.GetBytes(c), 0, sizeof(char));
//Compress file content
byte[] bytes = File.ReadAllBytes(Path.Combine(sDir, sRelativePath));
zipStream.Write(BitConverter.GetBytes(bytes.Length), 0, sizeof(int));
zipStream.Write(bytes, 0, bytes.Length);
}
public void CompressDirectory(string sInDir, string sOutFile)
{
string[] sFiles = Directory.GetFiles(sInDir, "*.*", SearchOption.AllDirectories);
int iDirLen = sInDir[sInDir.Length - 1] == Path.DirectorySeparatorChar ? sInDir.Length : sInDir.Length + 1;
using (FileStream outFile = new FileStream(sOutFile, FileMode.Create, FileAccess.Write, FileShare.None))
using (GZipStream str = new GZipStream(outFile, CompressionMode.Compress))
foreach (string sFilePath in sFiles)
{
string sRelativePath = sFilePath.Substring(iDirLen);
CompressFile(sInDir, sRelativePath, str);
}
}
the result of above code is a zip file that contains a file with unknown format.
Please reply to me how can i zip(compress) a directory in Asp.net 2 (IIS 6)?
This is dealing with .NET 2.0 application, and you for some reason cannot upgrade the IIS and corresponding .NET Framework to a newer version (which for security reasons, you really should). Of course, the following also applies to .NET 3, 3.5 and 4.
For .NET 2.0 the System.IO.Compression namespace only supports GZip (.gz) files, and requires having that application to uncompress. GZip is a standard part of GNU, and I believe that 7Zip provides an easy to use Windows accessible tool for working with them.
That said, there are .Net libraries that can help create actual ZIP files for you; for example Dino's DotNetZip (https://github.com/DinoChiesa/DotNetZip). They can just be a bit hard to find for a framework as old as .NET 2 or even 3.5 these days.
DotNetZip does require .NET 3.5 to build, but once a DLL is generated, the documentation says that DLL can be integrated and used in a .NET 2.0 application. Using it is fairly simple:
As I mentioned, other libraries do exist, but I know this one works well as I've used it in the past.
Now, if you are using a more modern version of .NET (basically 4.5 or later), you can use the ZipFile type inside the System.IO.Compression namespace. Which is very easy to use: