溫馨提示×

C#壓縮文件操作如何進行

c#
小樊
158
2024-07-11 09:38:38
欄目: 編程語言

在C#中,可以使用System.IO.Compression命名空間中的類來進行文件的壓縮和解壓縮操作。具體來說,可以使用ZipArchive類來創建和打開ZIP文件,并使用ZipFile類來實現文件的壓縮和解壓縮。

以下是一個簡單的示例代碼,演示如何使用ZipFile類來進行文件的壓縮和解壓縮操作:

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

class Program
{
    static void Main()
    {
        string sourceFile = @"C:\example.txt";
        string compressedFile = @"C:\example.zip";
        string decompressedFile = @"C:\decompressed.txt";

        // 壓縮文件
        using (FileStream fs = new FileStream(compressedFile, FileMode.Create))
        {
            using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Create))
            {
                archive.CreateEntryFromFile(sourceFile, Path.GetFileName(sourceFile));
            }
        }

        Console.WriteLine("文件已成功壓縮為: " + compressedFile);

        // 解壓縮文件
        using (ZipArchive archive = ZipFile.OpenRead(compressedFile))
        {
            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                entry.ExtractToFile(decompressedFile, true);
            }
        }

        Console.WriteLine("文件已成功解壓為: " + decompressedFile);
    }
}

在上面的示例代碼中,首先創建了一個ZipArchive對象來表示要壓縮的文件,然后調用CreateEntryFromFile方法將源文件添加到壓縮文件中。接著使用ZipFile類的OpenRead方法打開壓縮文件,并通過遍歷ZipArchive對象的Entries屬性來將壓縮文件中的文件解壓縮到指定路徑下。

請注意,要使用以上代碼示例,需要在項目中添加對System.IO.Compression命名空間的引用。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女