How to compress a directory with the built in .net compression classes?

前端 未结 6 814
囚心锁ツ
囚心锁ツ 2021-01-15 19:15

Using the System.IO.Compression namespaces classes GZIPStream and DeflateStream I successfully can compress and decompress individual files. However, if I pass a directoryna

6条回答
  •  醉梦人生
    2021-01-15 19:42

    The classes in System.IO.Compression will only handle streams, yes. You'll have to do file handling yourself. You could, I suppose, use SharpZipLib or similar to tar the files, then compress the resulting tar file. Simple as (untested):

    using (Stream out = new FileStream("out.tar", FileMode.CreateNew))
    {
        TarArchive archive = TarArchive.CreateOutputTarArchive(outStream
                                        , TarBuffer.DefaultBlockFactor);
        foreach (string name in fileNames)
        {
            TarEntry entry = TarEntry.CreateEntryFromFile(name);
            archive.WriteEntry(entry, true);
        }
    }
    

提交回复
热议问题