.NET压缩文件

11

使用C#压缩文件的最佳方法是什么?理想情况下,我希望能够将多个文件分别压缩成一个归档文件。


转换后的文本:重复的问题 https://dev59.com/bXRC5IYBdhLWcg3wK96V - Ruben Bartelink
@Ruben:那就投票关闭... - H H
2
你应该停止担心并喜欢重复。 - user1228
6个回答

14

你可以使用DotNetZip来实现这个功能。它可以在任何应用程序中免费使用。

下面是一些示例代码:

   try
   {
     // for easy disposal
     using (ZipFile zip = new ZipFile())
     {
       // add this map file into the "images" directory in the zip archive
       zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
       // add the report into a different directory in the archive
       zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
       zip.AddFile("ReadMe.txt");
       zip.Save("MyZipFile.zip");
     }
   }
   catch (System.Exception ex1)
   {
     System.Console.Error.WriteLine("exception: " + ex1);
   }

1
我刚刚在DotNetZip中添加了多线程压缩算法。由于压缩是计算密集型的,使用多个线程可以显著提高在多核机器上处理大文件时的速度。根据我的测试,在压缩大型存档文件时,相比没有多线程支持的DotNetZip,它可以节省45%的时间。而编程模型并没有改变——外部代码是相同的,只有内部发生了变化。要获得这种加速效果,您需要使用v1.9.0.29版本。 - Cheeso

7

3

看看这个库: http://www.icsharpcode.net/OpenSource/SharpZipLib/

它非常全面,处理许多格式,是开源的,您可以在闭源商业应用程序中使用。

它非常简单易用:

byte[] data1 = new byte[...];
byte[] data2 = new byte[...];
/*...*/

var path = @"c:\test.zip";
var zip = new ZipOutputStream(new FileStream(path, FileMode.Create))
            {
                IsStreamOwner = true
            }

zip.PutNextEntry("File1.txt");
zip.Write(data1, 0, data1.Length);

zip.PutNextEntry("File2.txt");
zip.Write(data2, 0, data2.Length);

zip.Close();
zip.Dispose();

3

你看过SharpZipLib吗?

我相信你可以使用System.IO.Packaging命名空间中的类构建zip文件,但每次我尝试去了解它,我都觉得相当困惑...


3

0

你好,我使用ShapLib库(可以在这里下载http://www.icsharpcode.net/opensource/sharpziplib/)创建了两个方法,想要分享给大家。它们非常容易使用,只需要传递源路径和目标路径(包括文件夹/文件和扩展名的完整路径)。希望能对你有所帮助!

//ALLYOURNAMESPACESHERE
using ...

//SHARPLIB
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

public static class FileUtils
{

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sourcePath"></param>
    /// <param name="targetPath"></param>
    public static void ZipFile(string sourcePath, string targetPath)
    {
        string tempZipFilePath = targetPath;
        using (FileStream tempFileStream = File.Create(tempZipFilePath, 1024))
        {
            using (ZipOutputStream zipOutput = new ZipOutputStream(tempFileStream))
            {
                // Zip with highest compression.
                zipOutput.SetLevel(9);
                DirectoryInfo directory = new DirectoryInfo(sourcePath);
                foreach (System.IO.FileInfo file in directory.GetFiles())
                {

                    // Get local path and create stream to it.
                    String localFilename = file.FullName;
                    //ignore directories or folders
                    //ignore Thumbs.db file since this probably will throw an exception
                    //another process could be using it. e.g: Explorer.exe windows process
                    if (!file.Name.Contains("Thumbs") && !Directory.Exists(localFilename))
                    {
                        using (FileStream fileStream = new FileStream(localFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            // Read full stream to in-memory buffer.
                            byte[] buffer = new byte[fileStream.Length];
                            fileStream.Read(buffer, 0, buffer.Length);

                            // Create a new entry for the current file.
                            ZipEntry entry = new ZipEntry(file.Name);
                            entry.DateTime = DateTime.Now;

                            // set Size and the crc, because the information
                            // about the size and crc should be stored in the header
                            // if it is not set it is automatically written in the footer.
                            // (in this case size == crc == -1 in the header)
                            // Some ZIP programs have problems with zip files that don't store
                            // the size and crc in the header.
                            entry.Size = fileStream.Length;
                            fileStream.Close();

                            // Update entry and write to zip stream.
                            zipOutput.PutNextEntry(entry);
                            zipOutput.Write(buffer, 0, buffer.Length);

                            // Get rid of the buffer, because this
                            // is a huge impact on the memory usage.
                            buffer = null;
                        }
                    }
                }

                // Finalize the zip output.
                zipOutput.Finish();

                // Flushes the create and close.
                zipOutput.Flush();
                zipOutput.Close();
            }
        }
    }

    public static void unZipFile(string sourcePath, string targetPath)
    {
        if (!Directory.Exists(targetPath))
            Directory.CreateDirectory(targetPath);

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourcePath)))
        {

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {

                if (theEntry.Name != String.Empty)
                {
                    using (FileStream streamWriter = File.Create(targetPath + "\\" + theEntry.Name))
                    {

                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

}


忘了提到这将完全忽略“Thumbs.db”文件(它们有点无用,我不想搞乱那些数据)。 - d1jhoni1b

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接