Use java.util develop a C#.net zip tools

类别:.NET开发 点击:0 评论:0 推荐:

1. Step 1: add reference to vjslib.dll under C:\$WIDOWS DIRECTORY$\Microsoft.NET\Framework\$VERSION NUMBER $\

2. using  java.util.zip;

3. code

/// <summary>
/// Zip single file
/// </summary>
/// <param name="FilePath">original file path : string like "c:\\intrafinity\\web\\scorm\\"</param>
/// <param name="FileName">original file name: string like "win2000.gif"</param>
/// <param name="ZipFileName">zipped file : string like "c:\\intrafinity\\web\\scorm\\new.zip"</param>

public static void ZipFile(string FilePath, string FileName, string ZipFileName)
{

ZipOutputStream os = new ZipOutputStream(new java.io.FileOutputStream(ZipFileName));
ZipEntry ze = new ZipEntry(FileName);
ze.setMethod(ZipEntry.DEFLATED);
os.putNextEntry(ze);

java.io.FileInputStream fs = new java.io.FileInputStream(string.Concat(FilePath,FileName));
sbyte[] buff = new sbyte[1024];
int n = 0;

while ((n = fs.read(buff, 0, buff.Length)) > 0)
{os.write(buff, 0, n);}

fs.close();
os.closeEntry();
os.close();

}

 

/// <summary>
/// Zip folder
/// </summary>
/// <param name="FolderName">folder name : string like "c:\\intrafinity\\web\\scorm\\"</param>
/// <param name="ZipFileName">zipped file: string like "c:\\intrafinity\\web\\s.zip"</param>
public static void ZipFolder(string FolderName, string ZipFileName)
{

ZipOutputStream os = new ZipOutputStream(new java.io.FileOutputStream(ZipFileName));
ZipFolder(FolderName, ZipFileName, "", os);
os.closeEntry();
os.close();

}

public static void ZipFolder(string FolderName, string ZipFileName, string Addon, ZipOutputStream os)
{

string[] strs1 = Directory.GetFiles(FolderName);
string[] strs2 = Directory.GetDirectories(FolderName);

for (int i = 0; i < (int)strs1.Length; i++)
{
string str1 = strs1[i];
FileInfo fileInfo = new FileInfo(str1);
ZipEntry ze = new ZipEntry(string.Concat(Addon,fileInfo.Name));
ze.setMethod(ZipEntry.DEFLATED);
os.putNextEntry(ze);

java.io.FileInputStream fs = new java.io.FileInputStream(string.Concat(FolderName, fileInfo.Name));
sbyte[] buff = new sbyte[1024];
int n = 0;

while ((n = fs.read(buff, 0, buff.Length)) > 0)
{
os.write(buff, 0, n);
}

fs.close();
}

for (int j = 0; j < (int)strs2.Length; j++)
{
string str2 = strs2[j];
DirectoryInfo directoryInfo = new DirectoryInfo(str2);

ZipFolder(string.Concat(FolderName, directoryInfo.Name, "\\"), ZipFileName, string.Concat(Addon, directoryInfo.Name,"\\"), os);
}

}


4. Notice: .NET Framework 1.1 and 1.0 have some bug with vjslib.dll, the zipped file will have some head errors, but the content is fine, it can still be opened by winzip and winrar, but you will have some problem when open the zipped file by using wjslib.dll in your code. Ironic?
Framework 2.0 fixed the problem.

5. another solution is http://msdn.microsoft.com/msdnmag/issues/03/06/ZipCompression/default.aspx

本文地址:http://com.8s8s.com/it/it42487.htm