C#文件压缩

/// <summary>
/// 文件压缩
/// </summary>
/// <param name="filesUrl">多个文件路径</param>
/// <param name="zipStr">压缩文件名</param>
public static void ZipFile(List<string> filesUrl, string zipStr)
{
try
{

//这行代码表示文件名称有中文字。不然好像会出现乱码
Encoding gbk = Encoding.GetEncoding("gbk");
ZipConstants.DefaultCodePage = gbk.CodePage;
if (filesUrl != null && filesUrl.Count > 0)
{
ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipStr));
zipStream.SetLevel(6);
foreach (string itemStr in filesUrl)
{
zip(itemStr, zipStream);
}
zipStream.Finish();
zipStream.Close();
}
}
catch (Exception ex)
{
Common.SetException("类库", ex);
}
}
/// <summary>
/// 填写文件
/// </summary>
/// <param name="fileStr">文件路径</param>
/// <param name="zipStream"></param>
private static void zip(string fileStr, ZipOutputStream zipStream)
{
try
{
Crc32 crc = new Crc32();
if (File.Exists(fileStr))
{
FileStream fs = File.OpenRead(fileStr);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(fileStr.Substring(fileStr.LastIndexOf("\\") + 1));

entry.DateTime = DateTime.Now;
entry.Size = fs.Length;

fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipStream.PutNextEntry(entry);
zipStream.Write(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
Common.SetException("类库", ex);
}
}

压缩DLL下载 https://files.cnblogs.com/files/changeMe/SharpZipLib.rar

posted @ 2015-04-13 10:10  只需要一个眼神  阅读(208)  评论(0编辑  收藏  举报