c# 文件壓縮zip或?qū)ip文件解壓的方法
更新時間:2018年03月22日 09:17:43 作者:FeiJerry
下面小編就為大家分享一篇c# 文件壓縮zip或?qū)ip文件解壓的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
1.必須Dll:
ICSharpCode.SharpZipLib.dll??蓮腘utget程序包中獲取。
2.壓縮文件
/// <summary>
/// 壓縮文件成zip
/// </summary>
/// <param name="fileZip">壓縮成zip文件的絕對路徑</param>
/// <param name="fileName">被壓縮指定文件的名字</param>
/// <param name="zipFilePath"></param>
/// <returns></returns>
public bool CreateZipFile(string fileZip,string fileName, string zipFilePath)
{
bool isZip = false;
if (!Directory.Exists(zipFilePath))
{
Logger.Info($"Cannot find directory {zipFilePath}", false, "FileToZip");
return isZip;
}
try
{
string[] filenames = Directory.GetFiles(zipFilePath);
using (ZipOutputStream s = new ZipOutputStream(File.Create(fileZip)))
{
s.SetLevel(9); // 壓縮級別 0-9
//s.Password = "123"; //Zip壓縮文件密碼
byte[] buffer = new byte[4096]; //緩沖區(qū)大小
foreach (string file in filenames.ToList())
{
if (file== zipFilePath+fileName)//指定被壓縮文件的絕對路徑
{
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);
fs.Close();
fs.Dispose();
}
break;
}
}
s.Finish();
s.Close();
isZip = true;
}
}
catch (Exception ex)
{
Logger.Info($"Exception during processing {0}", false, "FileToZip");
}
return isZip;
}
3.將zip文件解壓
/// <summary>
/// 解壓文件
/// </summary>
/// <param name="zipFilePath">壓縮文件的絕對路徑</param>
public void UnZipFile(string zipFilePath)
{
if (!File.Exists(zipFilePath))
{
Logger.Info($"Cannot find file {zipFilePath}", false, "FileToZip");
return;
}
using (ZipInputStream 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);
// create directory
if (directoryName?.Length > 0)
{
Directory.CreateDirectory(directoryName);
}
if (!string.IsNullOrEmpty(fileName))
{
using (FileStream streamWriter = File.Create(theEntry.Name))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
4.其它:其中的Logger是Log4的用法。
以上這篇c# 文件壓縮zip或?qū)ip文件解壓的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#獲取機器碼的方法詳解(機器名,CPU編號,硬盤編號,網(wǎng)卡mac等)
這篇文章主要介紹了C#獲取機器碼的方法,結(jié)合實例形式詳細分析了C#獲取硬件機器名、CPU編號、硬盤編號、網(wǎng)卡mac等信息的相關(guān)實現(xiàn)方法,需要的朋友可以參考下2016-07-07

