Định dạng 7z là một lựa chọn phổ biến cho tỷ lệ cao nén và phân phối. Với Aspose.ZIP cho .NET, bạn có thể tạo tài liệu 7Z theo chương trình bằng cách sử dụng một API đơn giản, hiện đại. Hướng dẫn này đi qua một ví dụ làm việc tối thiểu và thêm các mô hình thực tế cho các dự án thực sự, chẳng hạn như thêm tệp từ đĩa, truyền dữ liệu từ bộ nhớ, kiểm soát tên nhập và thư mục bên trong hồ sơ, và xử lý lỗi cơ bản.

Tất cả các mẫu mã là inline và tự chứa.

Nguyên tắc

  • .NET 6 hoặc hơn
  • gói NuGet Aspose.Zip
dotnet add package Aspose.Zip

Tên không gian được sử dụng trong các mẫu:Aspose.Zip, Aspose.Zip.SevenZip

Khởi động nhanh: Tạo một tập tin 7z với một vài tệp

Ví dụ tối thiểu này tạo ra một lưu trữ 7z mới trong bộ nhớ, thêm hai bản ghi và lưu nó vào ổ đĩa.

// File: Program.cs
using System;
using System.IO;
using System.Text;
using Aspose.Zip.SevenZip;

class Program
{
    static void Main()
    {
        var outputPath = "example.7z";

        using (var archive = new SevenZipArchive())
        {
            // Add a text file from memory
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("Hello 7z from Aspose.ZIP")))
            {
                archive.CreateEntry("docs/readme.txt", ms);
            }

            // Add a file from disk
            var sourceFile = "report.pdf"; // ensure this file exists
            if (File.Exists(sourceFile))
            {
                using var fs = File.OpenRead(sourceFile);
                archive.CreateEntry("reports/2025/report.pdf", fs);
            }

            // Save the 7z archive
            using var outStream = File.Create(outputPath);
            archive.Save(outStream);
        }

        Console.WriteLine("Saved 7z: " + Path.GetFullPath(outputPath));
    }
}
  • Những điều cần lưu ý *
  • SevenZipArchive bắt đầu trống rỗng, sau đó bạn gọi CreateEntry(entryName, stream) theo mục.
  • Tên nhập định nghĩa cấu trúc thư mục bên trong tài liệu, chẳng hạn như: docs/readme.txt.
  • Bạn có thể đọc bất kỳ Stream, đó là hữu ích cho dữ liệu mà bạn tạo trong bộ nhớ.

Thêm một cây thư mục đầy đủ

Đi bộ một thư mục một cách lặp lại, bảo tồn cấu trúc tương đối của nó bên trong hồ sơ, và lưu như .7z.

using System;
using System.IO;
using Aspose.Zip.SevenZip;

static class FolderTo7z
{
    public static void CreateFromFolder(string sourceDir, string output7z)
    {
        if (!Directory.Exists(sourceDir))
            throw new DirectoryNotFoundException(sourceDir);

        using var archive = new SevenZipArchive();

        var basePath = Path.GetFullPath(sourceDir);
        foreach (var filePath in Directory.GetFiles(basePath, "*", SearchOption.AllDirectories))
        {
            var relPath = Path.GetRelativePath(basePath, filePath)
                              .Replace(Path.DirectorySeparatorChar, '/'); // normalize to forward slashes

            using var fs = File.OpenRead(filePath);
            archive.CreateEntry(relPath, fs);
        }

        using var outStream = File.Create(output7z);
        archive.Save(outStream);
    }
}

// Usage
// FolderTo7z.CreateFromFolder(@"C:\data\input", "bundle.7z");
  • Lời khuyên *
  • Sử dụng Path.GetRelativePath để giữ cho bố trí thư mục nội bộ sạch sẽ.
  • Tiêu chuẩn hóa các bộ phân tách con đường để tiếp tục rò rỉ cho các bản ghi lưu trữ nhất quán.

Stream file lớn một cách an toàn

Khi thêm các tập tin lớn, lưu chúng thay vì buffering toàn bộ tệp trong bộ nhớ. File.OpenRead Nếu bạn tạo nội dung trên máy bay, hãy viết nó vào một Stream và thông qua dòng chảy này trực tiếp đến CreateEntry.

using System.IO;
using System.Text;
using Aspose.Zip.SevenZip;

static void AddGeneratedCsv(SevenZipArchive archive, string entryName)
{
    // Example generator that writes CSV rows in a forward-only fashion
    using var pipe = new MemoryStream();
    using var writer = new StreamWriter(pipe, Encoding.UTF8, leaveOpen: true);

    writer.WriteLine("id,name");
    for (int i = 1; i <= 1000; i++)
        writer.WriteLine($"{i},Item {i}");

    writer.Flush();
    pipe.Position = 0;

    archive.CreateEntry(entryName, pipe);
}

Tổ chức các bài đăng với một trợ lý

Đối với các công việc lớn hơn, sử dụng một trợ lý nhỏ để thêm tệp với một bản cài đặt phổ biến. điều này giữ cho cấu trúc lưu trữ của bạn có thể dự đoán được.

using System.IO;
using Aspose.Zip.SevenZip;

static class SevenZipHelpers
{
    public static void AddFile(SevenZipArchive archive, string rootPrefix, string fullPath)
    {
        var relName = Path.Combine(rootPrefix, Path.GetFileName(fullPath))
                           .Replace(Path.DirectorySeparatorChar, '/');
        using var fs = File.OpenRead(fullPath);
        archive.CreateEntry(relName, fs);
    }
}

Ví dụ cuối cùng với logging và kiểm tra cơ bản

Ví dụ này tạo ra một tập tin 7z từ một danh sách hỗn hợp các nguồn. nó xác nhận các con đường và ghi kết quả.

// File: BuildArchive.cs
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.Zip.SevenZip;

public static class BuildArchive
{
    public static bool Run(IEnumerable<string> paths, string output7z)
    {
        if (paths == null) throw new ArgumentNullException(nameof(paths));
        Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output7z)) ?? ".");

        int added = 0, skipped = 0;

        using var archive = new SevenZipArchive();

        foreach (var p in paths)
        {
            if (string.IsNullOrWhiteSpace(p)) { skipped++; continue; }

            if (File.Exists(p))
            {
                using var fs = File.OpenRead(p);
                var entryName = Path.GetFileName(p);
                archive.CreateEntry(entryName, fs);
                Console.WriteLine("Added file: " + entryName);
                added++;
            }
            else if (Directory.Exists(p))
            {
                var basePath = Path.GetFullPath(p);
                foreach (var fp in Directory.GetFiles(basePath, "*", SearchOption.AllDirectories))
                {
                    var rel = Path.GetRelativePath(basePath, fp).Replace(Path.DirectorySeparatorChar, '/');
                    using var fs = File.OpenRead(fp);
                    archive.CreateEntry(rel, fs);
                    Console.WriteLine("Added: " + rel);
                    added++;
                }
            }
            else
            {
                Console.WriteLine("Skip missing: " + p);
                skipped++;
            }
        }

        using var outStream = File.Create(output7z);
        archive.Save(outStream);

        Console.WriteLine($"Saved: {Path.GetFullPath(output7z)}");
        Console.WriteLine($"Entries added: {added}, skipped: {skipped}");
        return added > 0;
    }
}

// Usage sample:
// BuildArchive.Run(new [] { "README.md", "assets", "docs/spec.pdf" }, "release.7z");

Thực hành tốt nhất

  • ** Sử dụng trước slashes cho tên nhập khẩu**Nhiều công cụ hiển thị các con đường một cách nhất quán hơn khi entries sử dụng / Giống như phân tách.

    • Có dòng chảy*Luôn xóa các file stream trong using Các mẫu ở trên đảm bảo phân phối sạch.
    • Chứng nhận nhập*Kiểm tra rằng các tập tin tồn tại trước khi thêm chúng. Cung cấp các sổ ghi chép rõ ràng cho các con đường bị bỏ qua.
    • Bảo vệ cấu trúc lưu trữ sạch sẽ*Quyết định về một tên thư mục gốc bên trong tài liệu và nhấp vào nó, chẳng hạn như: app/ hoặc package/.
    • Kiểm tra trên các nền tảng mục tiêu*Kiểm tra rằng 7z của bạn mở đúng trong các công cụ mà người dùng dựa vào.

Tổng hợp

Bạn đã tạo một tập tin 7z một cách lập trình với Aspose.ZIP cho .NET, thêm tệp từ đĩa và bộ nhớ, duy trì một cấu trúc thư mục sạch sẽ, và lưu kết quả cho .7zSử dụng các mô hình này để gói phát hành, gói và xuất khẩu trực tiếp từ ứng dụng C# của bạn.

More in this category