How to compress files

前端 未结 10 949
渐次进展
渐次进展 2021-02-01 06:58

I want to compress a file and a directory in C#. I found some solution in Internet but they are so complex and I couldn\'t run them in my project. Can anybody suggest me a clear

相关标签:
10条回答
  • 2021-02-01 07:26

    http://www.icsharpcode.net/opensource/sharpziplib/

    0 讨论(0)
  • 2021-02-01 07:31

    Source code taken from MSDN that is compatible to .Net 2.0 and above

    public static void CompressFile(string path)
            {
                FileStream sourceFile = File.OpenRead(path);
                FileStream destinationFile = File.Create(path + ".gz");
    
                byte[] buffer = new byte[sourceFile.Length];
            sourceFile.Read(buffer, 0, buffer.Length);
    
            using (GZipStream output = new GZipStream(destinationFile,
                CompressionMode.Compress))
            {
                Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
                    destinationFile.Name, false);
    
                output.Write(buffer, 0, buffer.Length);
            }
    
            // Close the files.
            sourceFile.Close();
            destinationFile.Close();
        }  
    
    0 讨论(0)
  • 2021-02-01 07:33

    I'm adding this answer as I've found an easier way than any of the existing answers:

    1. Install DotNetZip DLLs in your solution (easiest way is to install the package from nuget)
    2. Add a reference to the DLL.
    3. Import the namespace by adding: using Ionic.Zip;
    4. Zip your file

    Code:

    using (ZipFile zip = new ZipFile())
    {
        zip.AddFile("C:\test\test.txt");
        zip.AddFile("C:\test\test2.txt");
        zip.Save("C:\output.zip");
    }
    

    If you don't want the original folder structure mirrored in the zip file, then look at the overrides for AddFile() and AddFolder() etc.

    0 讨论(0)
  • 2021-02-01 07:33

    Use http://dotnetzip.codeplex.com/ to ZIP files or directory, there is no builtin class to do it directly in .NET

    0 讨论(0)
  • 2021-02-01 07:36

    There is a built-in class in System.IO.Packaging called the ZipPackage:

    http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage(v=vs.100).aspx

    0 讨论(0)
  • 2021-02-01 07:37

    You can just use ms-dos command line program compact.exe. Look on a parameters compact.exe in cmd and start this process using .NET method Process.Start().

    0 讨论(0)
提交回复
热议问题