目录使用ZipFile使用ZipArchive使用SharpZipLib使用第三方压缩软件C#压缩和解压文件及文件夹有以下几种方式:ZipFile(.NET 4.5 System.IO.Compression命名空间中新提供的压缩类) ZipArchive SharpZipLib和DotNetZip使用第三方压缩软件使用ZipFile引用.NET 4.5程序集:System.IO.Compression 和 System.IO.Compression.FileSystem.
public class CompressionHelper{/// /// 将指定目录压缩为Zip文件/// /// 文件夹地址 D:/1/ /// zip地址 D:/1.zip public static void CompressDirectoryZip(string folderPath, string zipPath){DirectoryInfo directoryInfo = new DirectoryInfo(zipPath);
if (directoryInfo.Parent != null){directoryInfo = directoryInfo.Parent;}
if (!directoryInfo.Exists){directoryInfo.Create();}
System.IO.Compression.ZipFile.CreateFromDirectory(folderPath, zipPath, CompressionLevel.Optimal, false);}
/// /// 将指定文件压缩为Zip文件/// /// 文件地址 D:/1.txt /// zip地址 D:/1.zip public static void CompressFileZip(string filePath, string zipPath){
FileInfo fileInfo = new FileInfo(filePath);string dirPath = fileInfo.DirectoryName?.Replace("\\", "/") + "/";string tempPath = dirPath + Guid.NewGuid() + "_temp/";if (!Directory.Exists(tempPath)){Directory.CreateDirectory(tempPath);}fileInfo.CopyTo(tempPath + fileInfo.Name);CompressDirectoryZip(tempPath, zipPath);DirectoryInfo directory = new DirectoryInfo(tempPath);if (directory.Exists){//将文件夹属性设置为普通,如:只读文件夹设置为普通directory.Attributes = FileAttributes.Normal;
directory.Delete(true);}}
/// /// 解压Zip文件到指定目录/// /// zip地址 D:/1.zip/// 文件夹地址 D:/1/public static void DecompressZip(string zipPath, string folderPath){DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
if (!directoryInfo.Exists){directoryInfo.Create();}
System.IO.Compression.ZipFile.ExtractToDirectory(zipPath, folderPath);}
}使用ZipArchive public class ZipArchiveHelper{public static void ZipFile(string sourceFilePath, string zipFilePath){System.IO.Compression.ZipFile.CreateFromDirectory(sourceFilePath, zipFilePath);
// 创建并添加被压缩文件using (FileStream zipFileToOpen = new FileStream(sourceFilePath, FileMode.Create)){using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create)){string filename = System.IO.Path.GetFileName(zipFilePath);ZipArchiveEntry readMeEntry = archive.CreateEntry(filename);using (System.IO.Stream stream = readMeEntry.Open()){byte[] bytes = System.IO.File.ReadAllBytes(zipFilePath);stream.Write(bytes, 0, bytes.Length);}}}}
/// /// 在压缩文件中添加文件/// /// /// public static void AddZipFile(string sourceFilePath, string zipFilePath){using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Create)){using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create)){string filename = System.IO.Path.GetFileName(sourceFilePath);ZipArchiveEntry readMeEntry = archive.CreateEntry(filename);using (System.IO.Stream stream = readMeEntry.Open()){byte[] bytes = System.IO.File.ReadAllBytes(sourceFilePath);stream.Write(bytes, 0, bytes.Length);}}}
}
/// /// 解压压缩文件/// /// /// public static void UzipFile(string zipFilePath, string unzipFilePath){using (FileStream instream = File.OpenRead(zipFilePath)){using (ZipArchive zip = new ZipArchive(instream)){
foreach (ZipArchiveEntry et in zip.Entries){using (Stream stream = et.Open()){using (FileStream fsout = File.Create(System.IO.Path.Combine(unzipFilePath, et.Name))){stream.CopyTo(fsout);}}}}}}}使用SharpZipLib public class SharpZipLib{/// /// 压缩文件夹/// /// 文件夹路径/// 压缩包设置密码(注:可为空)/// 压缩包路径+名称+后缀(注:可为空,默认同目录)/// public string ZipFiles(string dirPath, string password, string zipFilePath){if (zipFilePath == string.Empty){//压缩文件名为空时使用文件夹名+.zip zipFilePath = GetZipFilePath(dirPath);}try{string[] filenames = Directory.GetFiles(dirPath);using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))){s.SetLevel(9);s.Password = password;byte[] buffer = new byte[4096];foreach (string file in filenames){ZipEntry entry = new ZipEntry(Path.GetFileName(file));entry.DateTime = DateTime.Now;s.PutNextEntry(entry);using (FileStream fs = File.OpenRead(file)){int sourceBytes;do{sourceBytes = fs.Read(buffer, 0, buffer.Length);s.Write(buffer, 0, sourceBytes);} while (sourceBytes > 0);}}s.Finish();s.Close();}return zipFilePath;}catch (Exception ex){return ex.ToString();}}
/// /// 减压文件夹/// /// 压缩包地址+名称+后缀/// 密码(注:可为空)/// 减压后保存的路径(注:可为空,默认同目录)/// public string UnZips(string zipFilePath, string password, string unZippath){try{if (unZippath == string.Empty){//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹unZippath = GetUnZipFilePath(zipFilePath);}if (CreatePath(unZippath) && IsExistFilePath(zipFilePath)){string directoryName = Path.GetDirectoryName(unZippath);{using (ZipInputStream zipInStream = new ZipInputStream(File.OpenRead(zipFilePath))){zipInStream.Password = password;ZipEntry entry = zipInStream.GetNextEntry();do{using (FileStream fileStreamOut = File.Create(directoryName + "\\" + entry.Name)){int size = 2048;byte[] buffer = new byte[size];do{size = zipInStream.Read(buffer, 0, buffer.Length);fileStreamOut.Write(buffer, 0, size);} while (size > 0);fileStreamOut.Close();fileStreamOut.Dispose();}} while ((entry = zipInStream.GetNextEntry()) != null);zipInStream.Close();zipInStream.Dispose();return unZippath;}}}return "请确认压缩包文件地址与解压后保存地址是否可以访问!";}catch (Exception ex){return ex.ToString();}}
/// /// 压缩文件/// /// 文件路径+名称+后缀/// 压缩包设置密码(注:可为空)/// 压缩包路径+名称+后缀(注:可为空,默认同目录)public string ZipFile(string dirFilePath, string password, string zipFilePath){try{if (IsExistFilePath(dirFilePath)){if (zipFilePath == string.Empty){zipFilePath = GetZipFilePath(dirFilePath.Replace(Path.GetExtension(dirFilePath), ""));}string filename = Path.GetFileName(dirFilePath);FileStream streamToZip = new FileStream(dirFilePath, FileMode.Open, FileAccess.Read);FileStream zipFile = File.Create(zipFilePath);using (ZipOutputStream zipStream = new ZipOutputStream(zipFile)){ZipEntry zipEntry = new ZipEntry(filename);zipStream.PutNextEntry(zipEntry);zipStream.SetLevel(9);zipStream.Password = password;byte[] buffer = new byte[2048];System.Int32 size = streamToZip.Read(buffer, 0, buffer.Length);zipStream.Write(buffer, 0, size);while (size < streamToZip.Length){int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);zipStream.Write(buffer, 0, sizeRead);size += sizeRead;}zipStream.Finish();zipStream.Close();streamToZip.Close();}return zipFilePath;}return "请确认压缩包文件地址与解压后保存地址是否可以访问!";}catch (Exception ex){return ex.ToString();}}
/// /// 创建路径/// /// 路径/// public bool CreatePath(string path){try{if (!Directory.Exists(path)){Directory.CreateDirectory(path);return true;}return true;}catch (Exception){return false;}}
/// /// 文件是否存在/// /// 路劲+名称+后缀/// public bool IsExistFilePath(string filePath){if (!File.Exists(filePath)){return false;}return true;}
/// /// 获取默认压缩路径+文件名+后缀【.zip】/// /// 需要压缩的文件夹路径(注:不包含.后缀)/// 与压缩文件同一目录路径public string GetZipFilePath(string path){if (path.EndsWith("\\")){path = path.Substring(0, path.Length - 1);}return path + ".zip";}
/// /// 获取默认解压路径/// /// 需要解压的压缩包文件地址/// 与解压文件同一目录路径public string GetUnZipFilePath(string path){path = path.Replace(Path.GetFileName(path), Path.GetFileNameWithoutExtension(path));if (!path.EndsWith("/")){path += "/";}return path;}
/// /// 获取路径中所有文件/// /// 路径/// private Hashtable getAllFies(string path){Hashtable FilesList = new Hashtable();DirectoryInfo fileDire = new DirectoryInfo(path);if (fileDire.Exists){this.getAllDirFiles(fileDire, FilesList);this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);}this.getAllDirFiles(fileDire, FilesList);this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);return FilesList;}
/// /// 获取一个文件夹下的所有文件夹里的文件/// /// /// private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList){foreach (DirectoryInfo dir in dirs){foreach (FileInfo file in dir.GetFiles("*.*")){filesList.Add(file.FullName, file.LastWriteTime);}this.getAllDirsFiles(dir.GetDirectories(), filesList);}}
/// /// 获取一个文件夹下的文件/// /// 目录名称/// 文件列表HastTableprivate void getAllDirFiles(DirectoryInfo dir, Hashtable filesList){foreach (FileInfo file in dir.GetFiles("*.*")){filesList.Add(file.FullName, file.LastWriteTime);}}}使用第三方压缩软件 public class WinrarZip{public static bool Zip(string strzipPath, string strtxtPath, string password){try{System.Diagnostics.Process Process1 = new System.Diagnostics.Process();Process1.StartInfo.FileName = "Winrar.exe";Process1.StartInfo.CreateNoWindow = true;Process1.StartInfo.Arguments = " a -p" + password + " " + strzipPath + " " + strtxtPath;//strtxtPath = "c://freezip//";//Process1.StartInfo.Arguments = " x -p123456 " + strzipPath + " " + strtxtPath;Process1.Start();if (Process1.HasExited){return true;}return true;}catch (Exception){return false;}
}
public static bool UZip(string strzipPath, string strtxtPath, string password){try{System.Diagnostics.Process Process1 = new System.Diagnostics.Process();Process1.StartInfo.FileName = "Winrar.exe";Process1.StartInfo.CreateNoWindow = true;//Process1.StartInfo.Arguments = " a -p123456 " + strzipPath + " " + strtxtPath;//strtxtPath = "c://freezip//";Process1.StartInfo.Arguments = " x -p" + password + " " + strzipPath + " " + strtxtPath;Process1.Start();if (Process1.HasExited){return true;}return true;}catch (Exception){
return false;}
}}到此这篇关于基于C#实现压缩和解压文件及文件夹的文章就介绍到这了,更多相关C#压缩和解压文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:C#实现文件压缩与解压功能的示例代码C#使用SharpZipLib压缩解压文件C#通过cmd调用7z软件实现压缩和解压文件C#调用7z实现文件的压缩与解压详解C#压缩、解压文件夹/文件(带密码) C#使用GZipStream实现文件的压缩与解压c# 文件压缩zip或将zip文件解压的方法