C# 如何压缩文件

C# 如何压缩文件,c#,.net,io,compression,c#-2.0,C#,.net,Io,Compression,C# 2.0,我想压缩C#中的文件和目录。我在互联网上找到了一些解决方案,但它们太复杂了,我无法在我的项目中运行它们。有人能给我一个清晰有效的解决方案吗 用于压缩文件或目录,在.NET中没有内置类可以直接进行压缩在System.IO.Packaging中有一个内置类称为ZipPackage: 您可以在System.IO.Compression名称空间中使用GZipStream .NET 2.0. public static void CompressFile(string path) { FileSt

我想压缩C#中的文件和目录。我在互联网上找到了一些解决方案,但它们太复杂了,我无法在我的项目中运行它们。有人能给我一个清晰有效的解决方案吗

用于压缩文件或目录,在.NET中没有内置类可以直接进行压缩

System.IO.Packaging
中有一个内置类称为
ZipPackage


您可以在
System.IO.Compression
名称空间中使用
GZipStream

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


您只需使用ms dos命令行程序compact.exe即可。
查看cmd中的parameters compact.exe并使用.NET方法process.start()启动此过程。

我添加此答案,因为我找到了一种比现有答案更简单的方法:

  • 在解决方案中安装DLL(最简单的方法是从nuget安装)
  • 添加对DLL的引用
  • 通过添加以下内容导入命名空间:使用Ionic.Zip
  • 压缩你的文件
  • 代码:

    如果不想在zip文件中镜像原始文件夹结构,请查看AddFile()和AddFolder()等的覆盖。

    使用DotNetZip,ZipFile类上有一个AddDirectory()方法,可以满足您的需要:

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

    Bonne continuation…

    只需使用以下代码压缩文件

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

    对于.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的引用


    发件人:

    为什么不能在项目中运行它们?请参阅.net 4.0中可能重复的@BugFinder,例如,我在这里找到了一个解决方案,但我无法在项目中描述“ZipFile”。虽然我添加了“using System.IO.Compression;”库,但错误并没有消失。关于ZipFile有很多代码。关于C#可能有问题,我可以在C#中使用这个类吗?你下载了与你链接的代码一起使用的组件吗?在.NET 2.0中没有像用户一样可用的组件asked@aprogrammer不客气。很抱歉,我没有发布一些代码,但我不知道我的确切位置,我现在没有太多时间。谢谢你的解决方案,但我在这段代码中有一个关于“CopyTo”的错误。我无法解决这个问题。@Romil-不,名称空间在2.0中可用,我检查过了。您还可以在以下位置找到证据:@DarrenDavies,infle.CopyTo()函数在2.0中不可用。它在4.0及更高版本中可用。@Romil-我已经包括了.NET2.0。我试图使用这个截取的文件,但在到达文件路径时遇到了问题。我有错误吗?无法访问文件路径的原因是什么?谢谢@Arnaud F。我看到了这一点,但我的程序无法识别ZipFile。我如何在我的程序中描述它?我试图使用这个剪贴,但在到达文件路径时遇到了问题。我有错误吗?无法访问文件路径的原因是什么?请尝试在D:驱动器(而不是OS驱动器)上创建文件。您应该在windows 7中面临访问问题,在try…catch and verify中捕获异常。同意,这是最简单的,如果不是最简单的,也是最简单的。DotNetZip似乎已经多年没有维护了,而且在压缩某些大文件时存在一个错误:我发现使用无法可靠地将文件添加到归档文件的zip库太可怕了。有人能确认DotNetZip有问题吗?@PeterHuber是的,它确实有这个bug,但修复程序在你发布的链接上。
           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());
                            }
                        }
                    }
                }
            }
    
        }
    
    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);
            }
        }
    }