基于C#實現(xiàn)壓縮和解壓文件及文件夾
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
{
/// <summary>
/// 將指定目錄壓縮為Zip文件
/// </summary>
/// <param name="folderPath">文件夾地址 D:/1/ </param>
/// <param name="zipPath">zip地址 D:/1.zip </param>
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);
}
/// <summary>
/// 將指定文件壓縮為Zip文件
/// </summary>
/// <param name="filePath">文件地址 D:/1.txt </param>
/// <param name="zipPath">zip地址 D:/1.zip </param>
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)
{
//將文件夾屬性設(shè)置為普通,如:只讀文件夾設(shè)置為普通
directory.Attributes = FileAttributes.Normal;
directory.Delete(true);
}
}
/// <summary>
/// 解壓Zip文件到指定目錄
/// </summary>
/// <param name="zipPath">zip地址 D:/1.zip</param>
/// <param name="folderPath">文件夾地址 D:/1/</param>
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);
// 創(chuàng)建并添加被壓縮文件
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);
}
}
}
}
/// <summary>
/// 在壓縮文件中添加文件
/// </summary>
/// <param name="sourceFilePath"></param>
/// <param name="zipFilePath"></param>
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);
}
}
}
}
/// <summary>
/// 解壓壓縮文件
/// </summary>
/// <param name="zipFilePath"></param>
/// <param name="unzipFilePath"></param>
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
{
/// <summary>
/// 壓縮文件夾
/// </summary>
/// <param name="dirPath">文件夾路徑</param>
/// <param name="password">壓縮包設(shè)置密碼(注:可為空)</param>
/// <param name="zipFilePath">壓縮包路徑+名稱+后綴(注:可為空,默認(rèn)同目錄)</param>
/// <returns></returns>
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();
}
}
/// <summary>
/// 減壓文件夾
/// </summary>
/// <param name="zipFilePath">壓縮包地址+名稱+后綴</param>
/// <param name="password">密碼(注:可為空)</param>
/// <param name="unZippath">減壓后保存的路徑(注:可為空,默認(rèn)同目錄)</param>
/// <returns></returns>
public string UnZips(string zipFilePath, string password, string unZippath)
{
try
{
if (unZippath == string.Empty)
{
//解壓文件夾為空時默認(rèn)與壓縮文件同一級目錄下,跟壓縮文件同名的文件夾
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 "請確認(rèn)壓縮包文件地址與解壓后保存地址是否可以訪問!";
}
catch (Exception ex)
{
return ex.ToString();
}
}
/// <summary>
/// 壓縮文件
/// </summary>
/// <param name="dirFilePath">文件路徑+名稱+后綴</param>
/// <param name="password">壓縮包設(shè)置密碼(注:可為空)</param>
/// <param name="zipFilePath">壓縮包路徑+名稱+后綴(注:可為空,默認(rèn)同目錄)</param>
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 "請確認(rèn)壓縮包文件地址與解壓后保存地址是否可以訪問!";
}
catch (Exception ex)
{
return ex.ToString();
}
}
/// <summary>
/// 創(chuàng)建路徑
/// </summary>
/// <param name="path">路徑</param>
/// <returns></returns>
public bool CreatePath(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return true;
}
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 文件是否存在
/// </summary>
/// <param name="filePath">路勁+名稱+后綴</param>
/// <returns></returns>
public bool IsExistFilePath(string filePath)
{
if (!File.Exists(filePath))
{
return false;
}
return true;
}
/// <summary>
/// 獲取默認(rèn)壓縮路徑+文件名+后綴【.zip】
/// </summary>
/// <param name="path">需要壓縮的文件夾路徑(注:不包含.后綴)</param>
/// <returns>與壓縮文件同一目錄路徑</returns>
public string GetZipFilePath(string path)
{
if (path.EndsWith("\\"))
{
path = path.Substring(0, path.Length - 1);
}
return path + ".zip";
}
/// <summary>
/// 獲取默認(rèn)解壓路徑
/// </summary>
/// <param name="path">需要解壓的壓縮包文件地址</param>
/// <returns>與解壓文件同一目錄路徑</returns>
public string GetUnZipFilePath(string path)
{
path = path.Replace(Path.GetFileName(path), Path.GetFileNameWithoutExtension(path));
if (!path.EndsWith("/"))
{
path += "/";
}
return path;
}
/// <summary>
/// 獲取路徑中所有文件
/// </summary>
/// <param name="path">路徑</param>
/// <returns></returns>
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;
}
/// <summary>
/// 獲取一個文件夾下的所有文件夾里的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
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);
}
}
/// <summary>
/// 獲取一個文件夾下的文件
/// </summary>
/// <param name="strDirName">目錄名稱</param>
/// <param name="filesList">文件列表HastTable</param>
private 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;
}
}
}到此這篇關(guān)于基于C#實現(xiàn)壓縮和解壓文件及文件夾的文章就介紹到這了,更多相關(guān)C#壓縮和解壓文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
selenium.chrome寫擴展攔截或轉(zhuǎn)發(fā)請求功能
Selenium?WebDriver?是一組開源?API,用于自動測試?Web?應(yīng)用程序,利用它可以通過代碼來控制chrome瀏覽器,今天通過本文給大家介紹selenium?chrome寫擴展攔截或轉(zhuǎn)發(fā)請求功能,感興趣的朋友一起看看吧2022-07-07
C#實現(xiàn)Json轉(zhuǎn)DataTable并導(dǎo)出Excel的方法示例
這篇文章主要介紹了C#實現(xiàn)Json轉(zhuǎn)DataTable并導(dǎo)出Excel的方法,結(jié)合實例形式總結(jié)分析了Json轉(zhuǎn)換DataTable,以及DataTable導(dǎo)出Excel相關(guān)操作技巧,需要的朋友可以參考下2019-02-02
C#實現(xiàn)的文件上傳下載工具類完整實例【上傳文件自動命名】
這篇文章主要介紹了C#實現(xiàn)的文件上傳下載工具類,結(jié)合完整實例形式分析了C#操作文件上傳與下載功能,并且還可針對上傳文件自動命名以避免服務(wù)器中的文件名重復(fù),需要的朋友可以參考下2017-11-11

