62,046
社区成员
发帖
与我相关
我的任务
分享
/// 压缩文件
/// </summary>
/// <param name="sourceFilePath"></param>
/// <param name="destinationZipFilePath"></param>
public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
{
if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
{
sourceFilePath += System.IO.Path.DirectorySeparatorChar;
}
ZipOutputStream zipStream = new ZipOutputStream(System.IO.File.Create(destinationZipFilePath));
zipStream.SetLevel(6); // 压缩级别 0-9
CreateZipFiles(sourceFilePath, zipStream);
zipStream.Finish();
zipStream.Close();
}
private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream)
{
string[] files = Directory.GetDirectories(sourceFilePath);
for (int i = 0; i < files.Length; i++)
{
string[] file = Directory.GetFiles(files[i].ToString());
Crc32 crc = new Crc32();
foreach (string name in file)
{
FileStream fileStream = System.IO.File.OpenRead(name);
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
string filename = Path.GetFileName(name);
ZipEntry entry = new ZipEntry(filename); //filename是xxx.jpg
entry.DateTime = DateTime.Now;
entry.Size = fileStream.Length;
fileStream.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipStream.PutNextEntry(entry);
zipStream.Write(buffer, 0, buffer.Length);
}
}
}