如何用C#實(shí)現(xiàn)壓縮文件
一、單文件壓縮
場(chǎng)景,文件可能比較大,需要壓縮傳輸,比如上傳和下載
/// <summary>
/// 單文件壓縮
/// </summary>
/// <param name="sourceFile">源文件</param>
/// <param name="zipedFile">zip壓縮文件</param>
/// <param name="blockSize">緩沖區(qū)大小</param>
/// <param name="compressionLevel">壓縮級(jí)別</param>
public static void ZipFile(string sourceFile, string zipedFile, int blockSize = 1024, int compressionLevel = 6)
{
if (!File.Exists(sourceFile))
{
throw new System.IO.FileNotFoundException("The specified file " + sourceFile + " could not be found.");
}
var fileName = System.IO.Path.GetFileNameWithoutExtension(sourceFile);
FileStream streamToZip = new FileStream(sourceFile, FileMode.Open, FileAccess.Read);
FileStream zipFile = File.Create(zipedFile);
ZipOutputStream zipStream = new ZipOutputStream(zipFile);
ZipEntry zipEntry = new ZipEntry(fileName);
zipStream.PutNextEntry(zipEntry);
//存儲(chǔ)、最快、較快、標(biāo)準(zhǔn)、較好、最好 0-9
zipStream.SetLevel(compressionLevel);
byte[] buffer = new byte[blockSize];
int 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;
}
}
catch (Exception ex)
{
throw ex;
}
zipStream.Finish();
zipStream.Close();
streamToZip.Close();
}
說(shuō)明:26行,blocksize為緩存區(qū)大小,不能設(shè)置太大,如果太大也會(huì)報(bào)異常。26-38行,把文件通過(guò)FileStream流,讀取到緩沖區(qū)中,再寫(xiě)入到ZipOutputStream流。你可以想象,兩個(gè)管道,一個(gè)讀,另一個(gè)寫(xiě),中間是緩沖區(qū),它們的工作方式是同步的方式。想一下,能不能以異步的方式工作,讀的管道只管讀,寫(xiě)的管道只管寫(xiě)?如果是這樣一個(gè)場(chǎng)景,讀的特別快,寫(xiě)的比較慢,比如,不是本地寫(xiě),而是要經(jīng)過(guò)網(wǎng)絡(luò)傳輸,就可以考慮異步的方式。怎么做,讀者可以自行改造。關(guān)鍵一點(diǎn),流是有順序的,所以要保證順序的正確性即可。
二、多文件壓縮
這種場(chǎng)景也是比較多見(jiàn),和單文件壓縮類似,無(wú)非就是多循環(huán)幾次。
/// <summary>
/// 多文件壓縮
/// </summary>
/// <param name="zipfile">zip壓縮文件</param>
/// <param name="filenames">源文件集合</param>
/// <param name="password">壓縮加密</param>
public void ZipFiles(string zipfile, string[] filenames, string password = "")
{
ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(zipfile));
s.SetLevel(6);
if (password != "")
s.Password = Md5Help.Encrypt(password);
foreach (string file in filenames)
{
//打開(kāi)壓縮文件
FileStream fs = File.OpenRead(file);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
var name = Path.GetFileName(file);
ZipEntry entry = new ZipEntry(name);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
s.PutNextEntry(entry);
s.Write(buffer, 0, buffer.Length);
}
s.Finish();
s.Close();
}
說(shuō)明:21行,緩沖區(qū)大小直接為文件大小,所以一次讀完,沒(méi)有循環(huán)讀寫(xiě)。這種情況下,單個(gè)文件不能太大,比如超過(guò)1G。14行,可以為壓縮包設(shè)置密碼,MD5的生成方法如下:
public class Md5Help
{
/// <summary>
///32位 MD5加密
/// </summary>
/// <param name="str">加密字符</param>
/// <returns></returns>
public static string Encrypt(string str)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] encryptdata = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
return Convert.ToBase64String(encryptdata);
}
}
三、多文件異步壓縮
上面同步的壓縮的前提是,假設(shè)文件不大,而且文件數(shù)不多,但是現(xiàn)實(shí)是,不光文件大,而且文件數(shù)比較多。這種情況,就要考慮異步方法了。否則會(huì)阻塞主線程,就是我們平常說(shuō)的卡死
/// <summary>
/// 異步壓縮文件為zip壓縮包
/// </summary>
/// <param name="zipfile">壓縮包存儲(chǔ)路徑</param>
/// <param name="filenames">文件集合</param>
public static async void ZipFilesAsync(string zipfile, string[] filenames)
{
await Task.Run(() =>
{
ZipOutputStream s = null;
try
{
s = new ZipOutputStream(System.IO.File.Create(zipfile));
s.SetLevel(6); // 0 - store only to 9 - means best compression
foreach (string file in filenames)
{
//打開(kāi)壓縮文件
FileStream fs = System.IO.File.OpenRead(file);
var name = Path.GetFileName(file);
ZipEntry entry = new ZipEntry(name);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
s.PutNextEntry(entry);
//如果文件大于1G
long blockSize = 51200;
var size = (int)fs.Length;
var oneG = 1024 * 1024 * 1024;
if (size > oneG)
{
blockSize = oneG;
}
byte[] buffer = new byte[blockSize];
size = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, size);
while (size < fs.Length)
{
int sizeRead = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sizeRead);
size += sizeRead;
}
s.Flush();
fs.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("異步壓縮文件出錯(cuò):" + ex.Message);
}
finally
{
s?.Finish();
s?.Close();
}
});
}
四、壓縮文件夾
實(shí)際的應(yīng)用當(dāng)中,是文件和文件夾一起壓縮,所以這種情況,就干脆把要壓縮的東西全部放到一個(gè)文件夾,然后進(jìn)行壓縮。
主方法如下:
/// <summary>
/// 異步壓縮文件夾為zip壓縮包
/// </summary>
/// <param name="zipfile">壓縮包存儲(chǔ)路徑</param>
/// <param name="sourceFolder">壓縮包存儲(chǔ)路徑</param>
/// <param name="filenames">文件集合</param>
public static async void ZipFolderAsync(string zipfile, string sourceFolder, string[] filenames)
{
await Task.Run(() =>
{
ZipOutputStream s = null;
try
{
s = new ZipOutputStream(System.IO.File.Create(zipfile));
s.SetLevel(6); // 0 - store only to 9 - means best compression
CompressFolder(sourceFolder, s, sourceFolder);
}
catch (Exception ex)
{
Console.WriteLine("異步壓縮文件出錯(cuò):" + ex.Message);
}
finally
{
s?.Finish();
s?.Close();
}
});
}
壓縮的核心方法:
/// <summary>
/// 壓縮文件夾
/// </summary>
/// <param name="source">源目錄</param>
/// <param name="s">ZipOutputStream對(duì)象</param>
/// <param name="parentPath">和source相同</param>
public static void CompressFolder(string source, ZipOutputStream s, string parentPath)
{
string[] filenames = Directory.GetFileSystemEntries(source);
foreach (string file in filenames)
{
if (Directory.Exists(file))
{
CompressFolder(file, s, parentPath); //遞歸壓縮子文件夾
}
else
{
using (FileStream fs = System.IO.File.OpenRead(file))
{
var writeFilePath = file.Replace(parentPath, "");
ZipEntry entry = new ZipEntry(writeFilePath);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
s.PutNextEntry(entry);
//如果文件大于1G
long blockSize = 51200;
var size = (int)fs.Length;
var oneG = 1024 * 1024 * 1024;
if (size > oneG)
{
blockSize = oneG;
}
byte[] buffer = new byte[blockSize];
size = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, size);
while (size < fs.Length)
{
int sizeRead = fs.Read(buffer, 0, buffer.Length);
s.Write(buffer, 0, sizeRead);
size += sizeRead;
}
s.Flush(); //清除流的緩沖區(qū),使得所有緩沖數(shù)據(jù)都寫(xiě)入到文件中
fs.Close();
}
}
}
}
唯一需要注意的地方,可能解壓出來(lái)的目錄結(jié)構(gòu)和壓縮前的文件目錄不同,這時(shí)候檢查parentPath參數(shù),它在ZipEntry實(shí)體new的時(shí)候用,替換絕對(duì)路徑為當(dāng)前的相對(duì)路徑,也就是相對(duì)壓縮文件夾的路徑。
上面的方法比較復(fù)雜,還有一種相對(duì)簡(jiǎn)單的方式,直接調(diào)用api:
public static string ZipFolder(string sourceFolder, string zipFile)
{
string result = "";
try
{
//創(chuàng)建壓縮包
if (!Directory.Exists(sourceFolder)) return result = "壓縮文件夾不存在";
DirectoryInfo d = new DirectoryInfo(sourceFolder);
var files = d.GetFiles();
if (files.Length == 0)
{
//找子目錄
var ds = d.GetDirectories();
if (ds.Length > 0)
{
files = ds[0].GetFiles();
}
}
if (files.Length == 0) return result = "待壓縮文件為空";
System.IO.Compression.ZipFile.CreateFromDirectory(sourceFolder, zipFile);
}
catch (Exception ex)
{
result += "壓縮出錯(cuò):" + ex.Message;
}
return result;
}
以上就是如何用C#實(shí)現(xiàn)壓縮文件的詳細(xì)內(nèi)容,更多關(guān)于C#壓縮文件的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#實(shí)現(xiàn)Menu和ContextMenu自定義風(fēng)格及contextMenu自定義
ContextMenu 類表示當(dāng)用戶在控件或窗體的特定區(qū)域上單擊鼠標(biāo)右鍵時(shí)會(huì)顯示的快捷菜單,要想實(shí)現(xiàn)自定義的Menu和ContextMenu效果,大家可以通過(guò)派生ProfessionalColorTable類,下面小編把實(shí)現(xiàn)Menu和ContextMenu自定義風(fēng)格及ContextMenu自定義給大家整理一下2015-08-08
解析c#在未出現(xiàn)異常情況下查看當(dāng)前調(diào)用堆棧的解決方法
本篇文章是對(duì)c#在未出現(xiàn)異常情況下查看當(dāng)前調(diào)用堆棧的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

