前言:
這幾天做關於文件下載和壓縮的功能,覺得這些功能在大家的開發中肯定會用到,就把這些代碼進行粘貼出來,爲大家節省些時間。
代碼如下:使用下面的代碼之前需要下載一個壓縮所需要的dll文件。
下載鏈接:壓縮dll下載地址
/// <summary>
/// 將文件進行壓縮,返回的是壓縮後文件的名字
/// </summary>
/// <param name="preZipFilePath">壓縮之前的文件路徑</param>
/// <param name="LastZipFilePath">壓縮之後的文件路徑</param>
/// <param name="zipName">壓縮文件的名字</param>
/// <param name="Level">壓縮級別</param>
/// <param name="zipSize">壓縮大小</param>
/// <returns></returns>
public static string ZipFile(string preZipFilePath, string lastZipFilePath,string zipName,int level,int zipSize)
{
//如果文件沒有找到,則報錯
if (!System.IO.File.Exists(preZipFilePath))
{
throw new System.IO.FileNotFoundException("指定要壓縮的文件: " + preZipFilePath + " 不存在!");
}
//文件名稱
string ZipFileName = string.IsNullOrEmpty(zipName) ? lastZipFilePath + "\\" + new FileInfo(preZipFilePath).Name.Substring(0, new FileInfo(preZipFilePath).Name.LastIndexOf('.')) + ".zip" : lastZipFilePath + "\\" +zipName+ ".zip";
//string ZipFileName = Guid.NewGuid().ToString();//壓縮文件名
using (System.IO.FileStream ZipFile = System.IO.File.Create(ZipFileName))
{
using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile))
{
using (System.IO.FileStream StreamToZip = new System.IO.FileStream(preZipFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
string fileName = preZipFilePath.Substring(preZipFilePath.LastIndexOf("\\") + 1);
ZipEntry ZipEntry = new ZipEntry(fileName);
ZipStream.PutNextEntry(ZipEntry);
//設置壓縮級別
ZipStream.SetLevel(level);
//緩存大小
byte[] buffer = new byte[zipSize];
int sizeRead = 0;
try
{
do
{
sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
ZipStream.Write(buffer, 0, sizeRead);
}
while (sizeRead > 0);
}
catch (System.Exception ex)
{
throw ex;
}
StreamToZip.Close();
}
ZipStream.Finish();
ZipStream.Close();
}
ZipFile.Close();
}
return zipName;
}
代碼經過實際操作,大家直接用就好。
結尾:
分享:耐得住寂寞,穩得住心性,每天進步一點點!