使用SevenZipSharp壓縮/解壓7z格式


7z格式采用的LZMA算法,號稱具有現今最高壓縮率。筆者在nuget上搜索7z,在搜索結果中最終選擇了SevenZipSharp來進行壓縮/解壓。不得不說,SevenZipSharp的API設計得非常方便。

壓縮調用:

using (FileStream ostream = new FileStream(outputpath, FileMode.Create, FileAccess.Write))
{
    using (FileStream istream = new FileStream(inputpath, FileMode.Open, FileAccess.Read))
    {
        SevenZipCompressor compressor = new SevenZipCompressor();
        // 這里可以輸入多個文件名/流對
        Dictionary<string, Stream> dict = new Dictionary<string, Stream> { { inputpath, istream } };
        compressor.CompressStreamDictionary(dict, ostream);
    }
}

解壓調用:

using (FileStream istream = new FileStream(inputpath, FileMode.Open, FileAccess.Read))
{
    SevenZip.SevenZipExtractor extractor = new SevenZip.SevenZipExtractor(istream);
    extractor.ExtractArchive(outputpath);    // 全部解壓到指定目錄
    using (FileStream ostream = new FileStream(outputpath, FileMode.Create, FileAccess.Write))
    {
        extractor.ExtractFile(0, ostream);        // 流式解壓指定文件
    }
}

順便附上zlib的壓縮/解壓(使用zlib.net庫):

// 壓縮
static void Compress(string inputpath, string outputpath)
{
    using (FileStream ostream = new FileStream(outputpath, FileMode.Create, FileAccess.Write))
    {
        using (FileStream istream = new FileStream(inputpath, FileMode.Open, FileAccess.Read))
        {
            using (ZOutputStream zstream = new ZOutputStream(ostream, zlibConst.Z_BEST_COMPRESSION))
            {
                CopyStream(istream, zstream);
            }
        }
    }
}

// 解壓
static void Decompress(string inputpath, string outputpath)
{
    using (FileStream ostream = new FileStream(outputpath, FileMode.Create, FileAccess.Write))
    {
        using (FileStream istream = new FileStream(inputpath, FileMode.Open, FileAccess.Read))
        {
            using (ZOutputStream zstream = new ZOutputStream(ostream))
            {
                CopyStream(istream, zstream);
            }
        }
    }
}

static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[2000];
    int len;
    while ((len = input.Read(buffer, 0, 2000)) > 0)
    {
        output.Write(buffer, 0, len);
    }
    output.Flush();
}


免責聲明!

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



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