Подтвердить что ты не робот

Как сжать файлы

Я хочу сжать файл и каталог на С#. Я нашел какое-то решение в Интернете, но они настолько сложны, что я не смог запустить их в своем проекте. Может ли кто-нибудь предложить мне ясное и эффективное решение?

4b9b3361

Ответ 1

Вы можете использовать GZipStream в пространстве имен System.IO.Compression

.NET 2.0.

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();
}

.NET 4

public static void Compress(FileInfo fi)
    {
        // Get the stream of the source file.
        using (FileStream inFile = fi.OpenRead())
        {
            // Prevent compressing hidden and 
            // already compressed files.
            if ((File.GetAttributes(fi.FullName) 
                & FileAttributes.Hidden)
                != FileAttributes.Hidden & fi.Extension != ".gz")
            {
                // Create the compressed file.
                using (FileStream outFile = 
                            File.Create(fi.FullName + ".gz"))
                {
                    using (GZipStream Compress = 
                        new GZipStream(outFile, 
                        CompressionMode.Compress))
                    {
                        // Copy the source file into 
                        // the compression stream.
                    inFile.CopyTo(Compress);

                        Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                            fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                    }
                }
            }
        }
    }

http://msdn.microsoft.com/en-us/library/ms404280.aspx

Ответ 2

Я добавляю этот ответ, поскольку я нашел более простой способ, чем любой из существующих ответов:

  1. Установите DotNetZip DLL в свое решение (самый простой способ - установить пакет из nuget)
  2. Добавьте ссылку на DLL.
  3. Импортируйте пространство имен, добавив: using Ionic.Zip;
  4. Почтовый файл

Код:

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

Если вы не хотите, чтобы исходная структура папок была зеркалирована в zip файле, посмотрите на переопределения для AddFile() и AddFolder() и т.д.

Ответ 5

Вы можете просто использовать программу командной строки ms-dos compact.exe. Посмотрите на параметры compact.exe в cmd и запустите этот процесс с помощью метода.NET Process.Start().

Ответ 6

просто используйте следующий код для сжатия файла.

       public void Compressfile()
        {
             string fileName = "Text.txt";
             string sourcePath = @"C:\SMSDBBACKUP";
             DirectoryInfo di = new DirectoryInfo(sourcePath);
             foreach (FileInfo fi in di.GetFiles())
             {
                 //for specific file 
                 if (fi.ToString() == fileName)
                 {
                     Compress(fi);
                 }
             } 
        }

public static void Compress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Prevent compressing hidden and 
                // already compressed files.
                if ((File.GetAttributes(fi.FullName)
                    & FileAttributes.Hidden)
                    != FileAttributes.Hidden & fi.Extension != ".gz")
                {
                    // Create the compressed file.
                    using (FileStream outFile =
                                File.Create(fi.FullName + ".gz"))
                    {
                        using (GZipStream Compress =
                            new GZipStream(outFile,
                            CompressionMode.Compress))
                        {
                            // Copy the source file into 
                            // the compression stream.
                            inFile.CopyTo(Compress);

                            Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
                                fi.Name, fi.Length.ToString(), outFile.Length.ToString());
                        }
                    }
                }
            }
        }

    }

Ответ 7

Используйте http://dotnetzip.codeplex.com/ для ZIP файлов или каталога, нет встроенного класса, чтобы сделать это прямо в.NET.

Ответ 8

Исходный код, взятый из MSDN, совместимый с.Net 2.0 и выше

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();
    }  

Ответ 9

Используя DotNetZip http://dotnetzip.codeplex.com/, в классе ZipFile есть метод AddDirectory(), который делает то, что вы хотите:

using (var zip = new Ionic.Zip.ZipFile())
{
    zip.AddDirectory("DirectoryOnDisk", "rootInZipFile");
    zip.Save("MyFile.zip");
}

Продолжение Бонны...

Ответ 10

Для .Net Framework 4.5 это самый понятный пример, который я нашел:

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string startPath = @"c:\example\start";
            string zipPath = @"c:\example\result.zip";
            string extractPath = @"c:\example\extract";

            ZipFile.CreateFromDirectory(startPath, zipPath);

            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}

Вам нужно будет добавить ссылку на System.IO.Compression.FileSystem

От: https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files