/// <summary>
/// 多文件处理 压缩
/// </summary>
/// <param name="files">多个文件的物理路径(带后缀)</param>
/// <param name="ZipedFileName">压缩后的文件物理路径(带后缀)</param>
/// <param name="Password">压缩包密码</param>
/// <returns></returns>
public static bool ListZip(string[] files, string ZipedFileName, string Password = "")
{
var ret = false;
ZipOutputStream zipStream = null;
try
{
files = files.Where(f => File.Exists(f)).ToArray();
if (files.Length != 0)
{
zipStream = new ZipOutputStream(File.Create(ZipedFileName));
zipStream.SetLevel(6);
if (!string.IsNullOrEmpty(Password.Trim())) zipStream.Password = Password.Trim();
ZipFileDictory(files, zipStream, ZipedFileName);
ret = true;
}
}
finally
{
if (zipStream != null)
{
zipStream.Finish();
zipStream.Close();
}
}
return ret;
}
private static void ZipFileDictory(string[] files, ZipOutputStream s, string zipedFile)
{
ZipEntry entry = null;
FileStream fs = null;
Crc32 crc = new Crc32();
try
{
foreach (string file in files)
{
//打开压缩文件
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
var name = Path.Combine("", Path.GetFileName(zipedFile.Replace(".zip", "")), Path.GetFileName(file));
entry = new ZipEntry(name);
//因为帮助类里面少了这句代码,设置字符集,解决乱码
entry.IsUnicodeText = true;
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
s.Flush();
}
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (entry != null)
entry = null;
GC.Collect();
}
}