C# 壓縮文件 ICSharpCode.SharpZipLib.dll


效果:

代碼只能壓縮文件夾里面的文件,不能壓縮文件夾。

壓縮前:

壓縮后:

代碼:

需要引用ICSharpCode.SharpZipLib.dll

public ActionResult Index()
{
    //路徑
    string path = "E:/test/xls_Z";
    //調用
    CreateZip(path ,path + ".zip");
}

/// <summary>
/// 壓縮文件
/// </summary>
/// <param name="sourceFilePath">文件路徑</param>
/// <param name="destinationZipFilePath">壓縮后的地址</param>
public static void CreateZip(string sourceFilePath, string destinationZipFilePath)
{
    if (sourceFilePath[sourceFilePath.Length - 1] != System.IO.Path.DirectorySeparatorChar)
        sourceFilePath += System.IO.Path.DirectorySeparatorChar;
    ZipOutputStream zipStream = new ZipOutputStream(System.IO.File.Create(destinationZipFilePath));
    zipStream.SetLevel(6);  // 壓縮級別 0-9
    CreateZipFiles(sourceFilePath, zipStream);
    zipStream.Finish();
    zipStream.Close();
}

/// <summary>
/// 遞歸壓縮文件
/// </summary>
/// <param name="sourceFilePath">待壓縮的文件或文件夾路徑</param>
/// <param name="zipStream">打包結果的zip文件路徑(類似 D:\WorkSpace\a.zip),全路徑包括文件名和.zip擴展名
/// <param name="staticFile"></param>
private static void CreateZipFiles(string sourceFilePath, ZipOutputStream zipStream)
{
    Crc32 crc = new Crc32();
    string[] filesArray = Directory.GetFileSystemEntries(sourceFilePath);
    foreach (string file in filesArray)
    {
     //如果當前是文件夾,遞歸
        if (Directory.Exists(file))                     
        {
            CreateZipFiles(file, zipStream);
        }
     //如果是文件,開始壓縮
        else                                            
        {
            FileStream fileStream = System.IO.File.OpenRead(file);
            byte[] buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            string tempFile = file.Substring(sourceFilePath.LastIndexOf("\\") + 1);
            ZipEntry entry = new ZipEntry(tempFile);
            entry.DateTime = DateTime.Now;
            entry.Size = fileStream.Length;
            fileStream.Close();
            crc.Reset();
            crc.Update(buffer);
            entry.Crc = crc.Value;
            zipStream.PutNextEntry(entry);
            zipStream.Write(buffer, 0, buffer.Length);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM