簡體   English   中英

使用C#壓縮單個文件

[英]Compress a single file using C#

我正在使用.NET 4.5,如果我嘗試使用“CreateFromDirectory”壓縮整個目錄,ZipFile類的效果很好。 但是,我只想在目錄中壓縮一個文件。 我試着指向一個特定的文件(文件夾\\ data.txt),但這不起作用。 我考慮過ZipArchive類,因為它有一個“CreateEntryFromFile”方法,但似乎這只允許你創建一個現有文件的條目。

有沒有辦法簡單地壓縮一個文件而不創建一個空的zipfile(有問題),然后使用ZipArchiveExtension的“CreateEntryFromFile”方法?

**這也是假設我正在開發一個目前無法使用第三方附加組件的公司計划。

示例來自: 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);

但是如果startPath是@"c:\\example\\start\\myFile.txt;" ,它會拋出一個目錄無效的錯誤。

使用CreateEntryFromFile關閉存檔並使用文件或內存流:

如果您可以創建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");
}

或者,如果您需要在內存中執行所有操作並在文件完成后寫入文件,請使用內存流:

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

然后,您可以將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 (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);
}

或者更簡潔:

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

確保添加對System.IO.Compression的引用

更新

另外,請查看ZipFileZipArchive的新dotnet API文檔。 那里有幾個例子。 還有關於引用System.IO.Compression.FileSystem以使用ZipFile的警告。

要使用ZipFile類,必須在項目中引用System.IO.Compression.FileSystem程序集。

最簡單的方法是使用臨時文件夾。

用於拉鏈:

  1. 創建臨時文件夾
  2. 將文件移動到文件夾
  3. ZIP文件夾
  4. 刪除文件夾

解凍:

  1. 解壓縮檔案
  2. 將文件從臨時文件夾移動到您的位置
  3. 刪除臨時文件夾

在.NET中,對於單個文件,有很多方法可以解決這個問題。 如果您不想學習那里的所有內容,您可以獲得一個抽象的庫,如SharpZipLib(長期開源庫),sevenzipsharp(需要下面的7zip庫)或DotNetZip。

只需使用以下代碼壓縮文件即可。

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