简体   繁体   English

使用C#压缩单个文件

[英]Compress a single file using C#

I am using .NET 4.5, and the ZipFile class works great if I am trying to zip up an entire directory with "CreateFromDirectory". 我正在使用.NET 4.5,如果我尝试使用“CreateFromDirectory”压缩整个目录,ZipFile类的效果很好。 However, I only want to zip up one file in the directory. 但是,我只想在目录中压缩一个文件。 I tried pointing to a specific file (folder\\data.txt), but that doesn't work. 我试着指向一个特定的文件(文件夹\\ data.txt),但这不起作用。 I considered the ZipArchive class since it has a "CreateEntryFromFile" method, but it seems this only allows you to create an entry into an existing file. 我考虑过ZipArchive类,因为它有一个“CreateEntryFromFile”方法,但似乎这只允许你创建一个现有文件的条目。

Is there no way to simply zip up one file without creating an empty zipfile (which has its issues) and then using the ZipArchiveExtension's "CreateEntryFromFile" method? 有没有办法简单地压缩一个文件而不创建一个空的zipfile(有问题),然后使用ZipArchiveExtension的“CreateEntryFromFile”方法?

**This is also assuming I am working on a company program which cannot use third-party add-ons at the moment. **这也是假设我正在开发一个目前无法使用第三方附加组件的公司计划。

example from: http://msdn.microsoft.com/en-us/library/ms404280%28v=vs.110%29.aspx 示例来自: http//msdn.microsoft.com/en-us/library/ms404280%28v=vs.110%29.aspx

        string startPath = @"c:\example\start";
        string zipPath = @"c:\example\result.zip";
        string extractPath = @"c:\example\extract";

        ZipFile.CreateFromDirectory(startPath, zipPath);

        ZipFile.ExtractToDirectory(zipPath, extractPath);

But if startPath were to be @"c:\\example\\start\\myFile.txt;" 但是如果startPath是@"c:\\example\\start\\myFile.txt;" , it would throw an error that the directory is invalid. ,它会抛出一个目录无效的错误。

Use the CreateEntryFromFile off a an archive and use a file or memory stream: 使用CreateEntryFromFile关闭存档并使用文件或内存流:

Using a filestream if you are fine creating the zip file and then adding to it: 如果您可以创建zip文件然后添加到文件流,请使用文件流:

using (FileStream fs = new FileStream(@"C:\Temp\output.zip",FileMode.Create))
using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create))
{
    arch.CreateEntryFromFile(@"C:\Temp\data.xml", "data.xml");
}

Or if you need to do everything in memory and write the file once it is done, use a memory stream: 或者,如果您需要在内存中执行所有操作并在文件完成后写入文件,请使用内存流:

using (MemoryStream ms = new MemoryStream())
using (ZipArchive arch = new ZipArchive(ms, ZipArchiveMode.Create))
{
    arch.CreateEntryFromFile(@"C:\Temp\data.xml", "data.xml");
}

Then you can write the MemoryStream to a file . 然后,您可以将MemoryStream写入文件

using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write)) {
   byte[] bytes = new byte[ms.Length];
   ms.Read(bytes, 0, (int)ms.Length);
   file.Write(bytes, 0, bytes.Length);
   ms.Close();
}

Using file (or any) stream: 使用文件(或任何)流:

using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
{
    var entry = zip.CreateEntry("file.txt");
    entry.LastWriteTime = DateTimeOffset.Now;

    using (var stream= File.OpenRead(@"c:\path\to\file.txt"))
    using (var entryStream = entry.Open())
        stream.CopyTo(entryStream);
}

or briefer: 或者更简洁:

// reference System.IO.Compression
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
    zip.CreateEntryFromFile("file.txt", "file.txt");

make sure you add references to System.IO.Compression 确保添加对System.IO.Compression的引用

Update 更新

Also, check out the new dotnet API documentation for ZipFile and ZipArchive too. 另外,请查看ZipFileZipArchive的新dotnet API文档。 There are a few examples there. 那里有几个例子。 There is also a warning about referencing System.IO.Compression.FileSystem to use ZipFile . 还有关于引用System.IO.Compression.FileSystem以使用ZipFile的警告。

To use the ZipFile class, you must reference the System.IO.Compression.FileSystem assembly in your project. 要使用ZipFile类,必须在项目中引用System.IO.Compression.FileSystem程序集。

The simplest way to get this working is to use a temporary folder. 最简单的方法是使用临时文件夹。

FOR ZIPPING: 用于拉链:

  1. Create a temp folder 创建临时文件夹
  2. Move file to folder 将文件移动到文件夹
  3. Zip folder ZIP文件夹
  4. Delete folder 删除文件夹

FOR UNZIPPING: 解冻:

  1. Unzip archive 解压缩档案
  2. Move file from temp folder to your location 将文件从临时文件夹移动到您的位置
  3. Delete temp folder 删除临时文件夹

In .NET, there are quite a few ways to tackle the problem, for a single file. 在.NET中,对于单个文件,有很多方法可以解决这个问题。 If you don't want to learn everything there, you can get an abstracted library, like SharpZipLib (long standing open source library), sevenzipsharp (requires 7zip libs underneath) or DotNetZip. 如果您不想学习那里的所有内容,您可以获得一个抽象的库,如SharpZipLib(长期开源库),sevenzipsharp(需要下面的7zip库)或DotNetZip。

just use following code for compressing a file. 只需使用以下代码压缩文件即可。

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

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM