1.使用第三方的压缩dll文件,引用的是(ICSharpCode.SharpZipLib.dll)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using System.Collections;
namespace Utility.SW.Common.Zip
{
public class ZipMgr : Singleton<ZipMgr>
{
public ZipMgr()
{
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="dirToZip"></param>
/// <param name="zipedFileName"></param>
/// <param name="compressionLevel">压缩率0(无压缩)9(压缩率最高)</param>
public void ZipDir(string dirToZip, string zipedFileName, int compressionLevel = 9)
{
if (Path.GetExtension(zipedFileName) != ".zip")
{
zipedFileName = zipedFileName + ".zip";
}
using (var zipoutputstream = new ZipOutputStream(File.Create(zipedFileName)))
{
zipoutputstream.SetLevel(compressionLevel);
Crc32 crc = new Crc32();
Hashtable fileList = GetAllFies(dirToZip);
foreach (DictionaryEntry item in fileList)
{
FileStream fs = new FileStream(item.Key.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
// ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(dirToZip.Length + 1));
ZipEntry entry = new ZipEntry(Path.GetFileName(item.Key.ToString()))
{
DateTime = (DateTime)item.Value,
Size = fs.Length
};
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, 0, buffer.Length);
}
}
}
/// <summary>
/// 获取所有文件
/// </summary>
/// <returns></returns>
public Hashtable GetAllFies(string dir)
{
Hashtable filesList = new Hashtable();
DirectoryInfo fileDire = new DirectoryInfo(dir);
if (!fileDire.Exists)
{
throw new FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
}
GetAllDirFiles(fileDire, filesList);
GetAllDirsFiles(fileDire.GetDirectories(), filesList);
return filesList;
}
/// <summary>
/// 获取一个文件夹下的所有文件夹里的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
public void GetAllDirsFiles(IEnumerable<DirectoryInfo> dirs, Hashtable filesList)
{
foreach (DirectoryInfo dir in dirs)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
GetAllDirsFiles(dir.GetDirectories(), filesList);
}
}
/// <summary>
/// 获取一个文件夹下的文件
/// </summary>
/// <param name="dir">目录名称</param>
/// <param name="filesList">文件列表HastTable</param>
public static void GetAllDirFiles(DirectoryInfo dir, Hashtable filesList)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
}
/// <summary>
/// 功能:解压zip格式的文件。
/// </summary>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
/// <returns>解压是否成功</returns>
public void UnZip(string zipFilePath, string unZipDir)
{
if (zipFilePath == string.Empty)
{
throw new Exception("压缩文件不能为空!");
}
if (!File.Exists(zipFilePath))
{
throw new FileNotFoundException("压缩文件不存在!");
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (unZipDir == string.Empty)
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
if (!unZipDir.EndsWith("/"))
unZipDir += "/";
if (!Directory.Exists(unZipDir))
Directory.CreateDirectory(unZipDir);
using (var s = new ZipInputStream(File.OpenRead(zipFilePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (!string.IsNullOrEmpty(directoryName))
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (directoryName != null && !directoryName.EndsWith("/"))
{
}
if (fileName != String.Empty)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{
int size;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
/// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="filePath">被压缩的文件名称(包含文件路径),文件的全路径</param>
/// <param name="zipedFileName">压缩后的文件名称(包含文件路径),保存的文件名称</param>
/// <param name="compressionLevel">压缩率0(无压缩)到 9(压缩率最高)</param>
public void ZipFile(string filePath, string zipedFileName, int compressionLevel = 9)
{
// 如果文件没有找到,则报错
if (!File.Exists(filePath))
{
throw new FileNotFoundException("文件:" + filePath + "没有找到!");
}
// 如果压缩后名字为空就默认使用源文件名称作为压缩文件名称
if (string.IsNullOrEmpty(zipedFileName))
{
string oldValue = Path.GetFileName(filePath);
if (oldValue != null)
{
zipedFileName = filePath.Replace(oldValue, "") + Path.GetFileNameWithoutExtension(filePath) + ".zip";
}
}
// 如果压缩后的文件名称后缀名不是zip,就是加上zip,防止是一个乱码文件
if (Path.GetExtension(zipedFileName) != ".zip")
{
zipedFileName = zipedFileName + ".zip";
}
// 如果指定位置目录不存在,创建该目录 C:\Users\yhl\Desktop\大汉三通
string zipedDir = zipedFileName.Substring(0, zipedFileName.LastIndexOf("\\", StringComparison.Ordinal));
if (!Directory.Exists(zipedDir))
{
Directory.CreateDirectory(zipedDir);
}
// 被压缩文件名称
string filename = filePath.Substring(filePath.LastIndexOf("\\", StringComparison.Ordinal) + 1);
var streamToZip = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var zipFile = File.Create(zipedFileName);
var zipStream = new ZipOutputStream(zipFile);
var zipEntry = new ZipEntry(filename);
zipStream.PutNextEntry(zipEntry);
zipStream.SetLevel(compressionLevel);
var buffer = new byte[2048];
Int32 size = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, size);
try
{
while (size < streamToZip.Length)
{
int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sizeRead);
size += sizeRead;
}
}
finally
{
zipStream.Finish();
zipStream.Close();
streamToZip.Close();
}
}
/// <summary>
/// 压缩单个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名,全路径</param>
/// <param name="zipedFile">压缩后生成的压缩文件名,全路径</param>
public void ZipFile(string fileToZip, string zipedFile)
{
// 如果文件没有找到,则报错
if (!File.Exists(fileToZip))
{
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
}
using (FileStream fileStream = File.OpenRead(fileToZip))
{
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, buffer.Length);
fileStream.Close();
using (FileStream zipFile = File.Create(zipedFile))
{
using (ZipOutputStream zipOutputStream = new ZipOutputStream(zipFile))
{
// string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1);
string fileName = Path.GetFileName(fileToZip);
var zipEntry = new ZipEntry(fileName)
{
DateTime = DateTime.Now,
IsUnicodeText = true
};
zipOutputStream.PutNextEntry(zipEntry);
zipOutputStream.SetLevel(5);
zipOutputStream.Write(buffer, 0, buffer.Length);
zipOutputStream.Finish();
zipOutputStream.Close();
}
}
}
}
/// <summary>
/// 压缩多个目录或文件
/// </summary>
/// <param name="folderOrFileList">待压缩的文件夹或者文件,全路径格式,是一个集合</param>
/// <param name="zipedFile">压缩后的文件名,全路径格式</param>
/// <param name="password">压宿密码</param>
/// <returns></returns>
public bool ZipManyFilesOrDictorys(IEnumerable<string> folderOrFileList, string zipedFile, string password)
{
bool res = true;
using (var s = new ZipOutputStream(File.Create(zipedFile)))
{
s.SetLevel(6);
if (!string.IsNullOrEmpty(password))
{
s.Password = password;
}
foreach (string fileOrDir in folderOrFileList)
{
//是文件夹
if (Directory.Exists(fileOrDir))
{
res = ZipFileDictory(fileOrDir, s, "");
}
else
{
//文件i
res = ZipFileWithStream(fileOrDir, s);
}
}
s.Finish();
s.Close();
return res;
}
}
/// <summary>
/// 带压缩流压缩单个文件
/// </summary>
/// <param name="fileToZip">要进行压缩的文件名</param>
/// <param name="zipStream"></param>
/// <returns></returns>
private bool ZipFileWithStream(string fileToZip, ZipOutputStream zipStream)
{
//如果文件没有找到,则报错
if (!File.Exists(fileToZip))
{
throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!");
}
//FileStream fs = null;
FileStream zipFile = null;
ZipEntry zipEntry = null;
bool res = true;
try
{
zipFile = File.OpenRead(fileToZip);
byte[] buffer = new byte[zipFile.Length];
zipFile.Read(buffer, 0, buffer.Length);
zipFile.Close();
zipEntry = new ZipEntry(Path.GetFileName(fileToZip));
zipStream.PutNextEntry(zipEntry);
zipStream.Write(buffer, 0, buffer.Length);
}
catch
{
res = false;
}
finally
{
if (zipEntry != null)
{
}
if (zipFile != null)
{
zipFile.Close();
}
GC.Collect();
GC.Collect(1);
}
return res;
}
/// <summary>
/// 递归压缩文件夹方法
/// </summary>
/// <param name="folderToZip"></param>
/// <param name="s"></param>
/// <param name="parentFolderName"></param>
private bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName)
{
bool res = true;
ZipEntry entry = null;
FileStream fs = null;
Crc32 crc = new Crc32();
try
{
//创建当前文件夹
entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); //加上 “/” 才会当成是文件夹创建
s.PutNextEntry(entry);
s.Flush();
//先压缩文件,再递归压缩文件夹
var filenames = Directory.GetFiles(folderToZip);
foreach (string file in filenames)
{
//打开压缩文件
fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
entry = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
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);
}
}
catch
{
res = false;
}
finally
{
if (fs != null)
{
fs.Close();
}
if (entry != null)
{
}
GC.Collect();
GC.Collect(1);
}
var folders = Directory.GetDirectories(folderToZip);
foreach (string folder in folders)
{
if (!ZipFileDictory(folder, s, Path.Combine(parentFolderName, Path.GetFileName(folderToZip))))
{
return false;
}
}
return res;
}
}
}
2.调用WinRAR方式
/// <summary>
/// 利用 WinRAR 进行压缩
/// </summary>
/// <param name="path">将要被压缩的文件夹(绝对路径)</param>
/// <param name="rarPath">压缩后的 .rar 的存放目录(绝对路径)</param>
/// <param name="rarName">压缩文件的名称(包括后缀)</param>
/// <returns>true 或 false。压缩成功返回 true,反之,false。</returns>
public bool RAR(string path, string rarPath, string rarName)
{
bool flag = false;
string rarexe; //WinRAR.exe 的完整路径
RegistryKey regkey; //注册表键
Object regvalue; //键值
string cmd; //WinRAR 命令参数
ProcessStartInfo startinfo;
Process process;
try
{
regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command");
regvalue = regkey.GetValue(""); // 键值为 "d:\Program Files\WinRAR\WinRAR.exe" "%1"
rarexe = regvalue.ToString();
regkey.Close();
rarexe = rarexe.Substring(1, rarexe.Length - 7); // d:\Program Files\WinRAR\WinRAR.exe
Directory.CreateDirectory(path);
path = "\"" + path + "\"";
//压缩命令,相当于在要压缩的文件夹(path)上点右键->WinRAR->添加到压缩文件->输入压缩文件名(rarName)
cmd = string.Format("a {0} {1} -ep1 -o+ -inul -r -ibck",
rarName,
path);
startinfo = new ProcessStartInfo();
startinfo.FileName = rarexe;
startinfo.Arguments = cmd; //设置命令参数
startinfo.WindowStyle = ProcessWindowStyle.Hidden; //隐藏 WinRAR 窗口
startinfo.WorkingDirectory = rarPath;
process = new Process();
process.StartInfo = startinfo;
process.Start();
process.WaitForExit(); //无限期等待进程 winrar.exe 退出
if (process.HasExited)
{
flag = true;
}
process.Close();
}
catch (Exception e)
{
throw e;
}
return flag;
}
/// <summary>
/// 利用 WinRAR 进行解压缩
/// </summary>
/// <param name="path">文件解压路径(绝对)</param>
/// <param name="rarPath">将要解压缩的 .rar 文件的存放目录(绝对路径)</param>
/// <param name="rarName">将要解压缩的 .rar 文件名(包括后缀)</param>
/// <returns>true 或 false。解压缩成功返回 true,反之,false。</returns>
public bool UnRAR(string path, string rarPath, string rarName)
{
bool flag = false;
string rarexe;
RegistryKey regkey;
Object regvalue;
string cmd;
ProcessStartInfo startinfo;
Process process;
try
{
regkey = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\open\command");
regvalue = regkey.GetValue("");
rarexe = regvalue.ToString();
regkey.Close();
rarexe = rarexe.Substring(1, rarexe.Length - 7);
Directory.CreateDirectory(path);
//解压缩命令,相当于在要压缩文件(rarName)上点右键->WinRAR->解压到当前文件夹
cmd = string.Format("x {0} {1} -y",
rarName,
path);
startinfo = new ProcessStartInfo();
startinfo.FileName = rarexe;
startinfo.Arguments = cmd;
startinfo.WindowStyle = ProcessWindowStyle.Hidden;
startinfo.WorkingDirectory = rarPath;
process = new Process();
process.StartInfo = startinfo;
process.Start();
process.WaitForExit();
if (process.HasExited)
{
flag = true;
}
process.Close();
}
catch (Exception e)
{
throw e;
}
return flag;
}
注意:如果路径中有空格(如:D:\Program Files\)的话压缩解压就会出现问题,需要在path 和 rarName 上加双引号,如: path = “\”” + path + “\”“;
附:RAR参数:
一、压缩命令
1、常用压缩参数
rar a -ep1 -o+ -inul -r -ibck temp.rar “c:\test*.*”
ep1:排除基准文件夹,不然压缩包会包含待压缩文件夹所在的完整路径
o+:覆盖已经存在的文件
inul:禁止出错信息
r:连同子文件夹操作
ibck:后台模式运行
2、将temp.txt压缩为temp.rar: rar a temp.rar temp.txt
3、将当前目录下所有文件压缩到temp.rar: rar a temp.rar .
4、将当前目录下所有文件及其所有子目录压缩到temp.rar: rar a temp.rar . -r
5、将当前目录下所有文件及其所有子目录压缩到temp.rar,并加上密码123rar a temp.rar . -r -p123
二、解压命令
1、将temp.rar解压到c:\temp目录rar e temp.rar c:\temprar e *.rar c:\temp(支持批量操作)
2、将temp.rar解压到c:\temp目录,并且解压后的目录结构和temp.rar中的目录结构一
压缩目录test及其子目录的文件内容
Wzzip test.zip test -r -P
WINRAR A test.rar test -r
删除压缩包中的*.txt文件
Wzzip test.zip *.txt -d
WinRAR d test.rar *.txt
刷新压缩包中的文件,即添加已经存在于压缩包中但更新的文件
Wzzip test.zip test -f
Winrar f test.rar test
更新压缩包中的文件,即添加已经存在于压缩包中但更新的文件以及新文件
Wzzip test.zip test -u
Winrar u test.rar test
移动文件到压缩包,即添加文件到压缩包后再删除被压缩的文件
Wzzip test.zip -r -P -m
Winrar m test.rar test -r
添加全部 *.exe 文件到压缩文件,但排除有 a或b
开头名称的文件
Wzzip test .exe -xf.* -xb*.*
WinRAR a test .exe -xf.* -xb*.*
加密码进行压缩
Wzzip test.zip test
-s123。注意密码是大小写敏感的。在图形界面下打开带密码的压缩文件,会看到+号标记(附图1)。
WINRAR A test.rar test -p123
-r。注意密码是大小写敏感的。在图形界面下打开带密码的压缩文件,会看到*号标记(附图2)。
按名字排序、以简要方式列表显示压缩包文件
Wzzip test.zip -vbn
Rar l test.rar
锁定压缩包,即防止未来对压缩包的任何修改
无对应命令
Winrar k test.rar
创建360kb大小的分卷压缩包
无对应命令
Winrar a -v360 test
带子目录信息解压缩文件
Wzunzip test -d
Winrar x test -r
不带子目录信息解压缩文件
Wzunzip test
Winrar e test
解压缩文件到指定目录,如果目录不存在,自动创建
Wzunzip test newfolder
Winrar x test newfolder
解压缩文件并确认覆盖文件
Wzunzip test -y
Winrar x test -y
解压缩特定文件
Wzunzip test *.txt
Winrar x test *.txt
解压缩现有文件的更新文件
Wzunzip test -f
Winrar x test -f
解压缩现有文件的更新文件及新文件
Wzunzip test -n
Winrar x test -u
批量解压缩文件
Wzunzip *.zip
WinRAR e *.rar
3.使用C#压缩解压库
SharpCompress是一个开源的压缩解压库,可以对RAR,7Zip,Zip,Tar,GZip,BZip2进行处理。
官方网址:http://sharpcompress.codeplex.com/
使用例子:
RAR文件解压缩:
using (Stream stream = File.OpenRead(@"C:\Code\sharpcompress.rar"))
{
var reader = ReaderFactory.Open(stream);
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Console.WriteLine(reader.Entry.FilePath);
reader.WriteEntryToDirectory(@"C:\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
}
}
}
ZIP文件解压缩:
var archive = ArchiveFactory.Open(@"C:\Code\sharpcompress\TestArchives\sharpcompress.zip");
foreach (var entry in archive.Entries)
{
if (!entry.IsDirectory)
{
Console.WriteLine(entry.FilePath);
entry.WriteToDirectory(@"C:\temp", ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
}
}
压缩为ZIP文件:
using (var archive = ZipArchive.Create())
{
archive.AddAllFromDirectoryEntry(@"C:\\source");
archive.SaveTo("@C:\\new.zip");
}
用Writer API创建ZIP文件
using (var zip = File.OpenWrite("C:\\test.zip"))
using (var zipWriter = WriterFactory.Open(ArchiveType.Zip, zip))
{
foreach (var filePath in filesList)
{
zipWriter.Write(Path.GetFileName(file), filePath);
}
}
创建tar.bz2
using (Stream stream = File.OpenWrite(tarPath))
using (var writer = WriterFactory.Open(ArchiveType.Tar, stream))
{
writer.WriteAll(filesPath, "*", SearchOption.AllDirectories);
}
using (Stream stream = File.OpenWrite(tarbz2Path))
using (var writer = WriterFactory.Open(ArchiveType.BZip2, stream))
{
writer.Write("Tar.tar", tarPath);
}
我们看到SharpCompress是没有压缩为rar的命令,因为所有RAR压缩文件都需要RAR作者的许可,你可以考虑压缩为zip或7zip,要不就使用WINRAR命令行压缩。
**以上都是学习 ^..^**