这是我迄今所知的最简单的压缩方法。使用了Java类库。
注意:必须在项目中添加对vjslib引用,程序才能通过编译。
{
String strDirectory = @"E:/工作";
static void Main(string[] args)
{
String zipFileName = "E://workBackup//" + DateTime.Now.ToString("yy_MM_dd") + ".zip";
//output stream
java.io.FileOutputStream fos = new java.io.FileOutputStream(zipFileName);
//tie to zip stream
java.util.zip.ZipOutputStream zos = new java.util.zip.ZipOutputStream(fos);
Program p = new Program();
Console.WriteLine("Enter a Directory/'s Name:" );
p.strDirectory = System.Console.ReadLine();
if (isDirectory(p.strDirectory))
{
p.zipFiles(p.strDirectory, zos);
}
else
{
Console.WriteLine("Directory is Inexistence.");
}
// Close everything
zos.closeEntry();
zos.close();
fos.close();
}
private static bool isDirectory(string p)
{
return System.IO.Directory.Exists(p);
}
private void zipFiles(String dir, java.util.zip.ZipOutputStream zos)
{
java.io.FileInputStream fis = null;
java.util.zip.ZipEntry ze = null;
//压缩目录中的文件
String[] strFiles = System.IO.Directory.GetFiles(dir);
foreach (String strfileName in strFiles)
{
// Stream with source file
fis = new java.io.FileInputStream(strfileName);
// It's our entry in zip
String strZipFileName = strfileName.Replace(strDirectory+"//", "");
ze = new java.util.zip.ZipEntry(strZipFileName);
zos.putNextEntry(ze);
sbyte[] buffer = new sbyte[1024];
int len;
// Read and write until done
while ((len = fis.read(buffer)) >= 0)
{
zos.write(buffer, 0, len);
}
//Close source stream
fis.close();
}
//深度优先遍历子目录
String[] subDirectories = System.IO.Directory.GetDirectories(dir);
foreach (String sdir in subDirectories)
{
zipFiles(sdir, zos);
}
}
}