1.需下載和引用文件“ICSharpCode.SharpZipLib.dll“。下載地址“https://download.csdn.net/download/njxiaogui/8251031”。
2.壓縮代碼的方法
/// <summary>
/// 壓縮單個(gè)文件
/// </summary>
/// <param name="fileToZip">要壓縮的文件</param>
/// <param name="zipedFile">壓縮后的文件全名</param>
/// <param name="compressionLevel">壓縮程度,范圍0-9,數(shù)值越大,壓縮程序越高</param>
/// <param name="blockSize">分塊大小</param>
public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
{
if (!System.IO.File.Exists(fileToZip))//如果文件沒(méi)有找到,則報(bào)錯(cuò)
{
throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");
}
FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
FileStream zipFile = File.Create(zipedFile);
ZipOutputStream zipStream = new ZipOutputStream(zipFile);
ZipEntry zipEntry = new ZipEntry(fileToZip);
zipStream.PutNextEntry(zipEntry);
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)
{
GC.Collect();
throw ex;
}
zipStream.Finish();
zipStream.Close();
streamToZip.Close();
GC.Collect();
}
3.調(diào)用方法。
ZipUtility zip = new ZipUtility();
zip.ZipFile(vidurl, vidrar, 5, 10);
// 該方法中 vidurl 為 要壓縮的絕對(duì)路徑
// vidrar 為壓縮文件所存放的路勁
4.總結(jié),該方法可以實(shí)現(xiàn)文件的在線(xiàn)壓縮,方便用戶(hù)下載不能直接下載的文件,比如視頻,音頻文件等。