先从网上下载ICSharpCode.SharpZipLib.dll类库
将文件或文件夹压缩为zip,函数如下
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileName">压缩文件路径</param>
/// <param name="zipName">压缩的文件名称</param>
/// <param name="error">返回的错误信息</param>
/// <returns></returns>
public bool FileToZip(string fileName, string zipName, out string error)
{
error = string.Empty;
try
{
ZipOutputStream s = new ZipOutputStream(File.Create(zipName));
s.SetLevel(); // 0 - store only to 9 - means best compression
zip(fileName, s);
s.Finish();
s.Close();
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
} private void zip(string fileName, ZipOutputStream s)
{
if (fileName[fileName.Length - ] != Path.DirectorySeparatorChar)
fileName += Path.DirectorySeparatorChar;
Crc32 crc = new Crc32();
string[] filenames = Directory.GetFileSystemEntries(fileName);
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
zip(file, s);
}
else // 否则直接压缩文件
{
//打开压缩文件
FileStream fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
string tempfile = Path.GetFileName(file);
ZipEntry entry = new ZipEntry(tempfile); 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, , buffer.Length);
}
}
}
将zip解压为文件或文件夹,函数代码如下
/// <summary>
/// 解压文件
/// </summary>
/// <param name="zipName">解压文件路径</param>
/// <param name="fileDirName">解压到文件夹的名称</param>
/// <param name="error">返回的错误信息</param>
/// <returns></returns>
public bool ZipToFile(string zipName, string fileDirName, out string error)
{
try
{
error = string.Empty;
//读取压缩文件(zip文件),准备解压缩
ZipInputStream s = new ZipInputStream(File.Open(zipName.Trim(), FileMode.Open, FileAccess.Read));
ZipEntry theEntry; string rootDir = " ";
while ((theEntry = s.GetNextEntry()) != null)
{
string path = fileDirName;
//获取该文件在zip中目录
rootDir = Path.GetDirectoryName(theEntry.Name);
//获取文件名称
string fileName = Path.GetFileName(theEntry.Name);
if (string.IsNullOrEmpty(fileName))
continue;
//判断是否为顶层文件,是,将文件直接放在fileDirName下,否,创建目录
if (string.IsNullOrEmpty(rootDir))
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
}
else
{
path += "\\" + rootDir;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
} //将文件流写入对应目录下的文件中
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(path + "\\" + fileName); int size = ;
byte[] data = new byte[];
while (true)
{
if (theEntry.Size == )
break; size = s.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
调用示例
string error;
if (FileToZip(@"E:\文档", "文档.zip", out error))
MessageBox.Show("Succee");
else
MessageBox.Show(error);
压缩示例
string error;
if (ZipToFile(@"E:\文档.zip", "文档", out error))
MessageBox.Show("Succee");
else
MessageBox.Show(error);
解压示例