您的位置:首页 > 编程语言 > C#

C# 压缩和解压文件(SharpZipLib)

2014-09-17 12:53 375 查看
先从网上下载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(6); // 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 - 1] != 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, 0, 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, 0, 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 = 2048;
byte[] data = new byte[2048];
while (true)
{
if (theEntry.Size == 0)
break;

size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
s.Close();
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}


调用示例

string error;
if (ZipToFile(@"E:\文档.zip", "文档", out error))
MessageBox.Show("Succee");
else
MessageBox.Show(error);


解压示例
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: