7z 格式是高比例压缩和分布的受欢迎选择. 使用 Aspose.ZIP for .NET,您可以通过一个简单而现代化的 API 编程创建 7Z 档案. 本指南通过最小的工作例子,并为实际项目添加了实用的模式,如从磁盘上加入文件,从内存中流动数据,控制存档中的输入名称和文件夹,以及基本错误处理。

所有代码样本都是内线和自我包含的。

原則

  • .NET 6 或更晚
  • NuGet 包 Aspose.Zip
dotnet add package Aspose.Zip

在样品中使用的名称空间:Aspose.Zip, Aspose.Zip.SevenZip

快速启动:使用几个文件创建7z档案

这个最小的例子在记忆中创建了一个新的7z档案,添加了两个输入,并将其存储在磁盘上。

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

“什么要注意”

  • SevenZipArchive 开始是空的,然后你打电话 CreateEntry(entryName, stream) 按项目。
  • 输入名称定义文件夹内部的结构,如 docs/readme.txt.
  • 你可以通过任何可读的 Stream,这对您在记忆中创建的数据有用。

添加一个完整的文件夹树

步行一个目录重复,保存其相对结构在档案中,并保存为 .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");
  • 提示 *
  • 使用 Path.GetRelativePath 保持内部文件夹的清洁。
  • 正常化路径分离器,以便进行一致的档案输入。

安全播放大文件

当添加大文件时,流动它们,而不是在内存中的整个文件。 File.OpenRead 如果您在飞机上创建内容,则将其写入一个 Stream 把这个流直接传到 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);
}

与助手安排入口

对于更大的工作,使用一个小助理添加文件与一个常见的预定,这保持您的档案结构可预测。

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

终端示例与登录和基本检查

此示例从一个混合的来源列表中创建了一个7z档案,它验证了路径和日志结果。

// 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");

最佳实践

  • ** 提前使用输入名称的插槽**许多工具在使用输入时更一致地显示路径 / 就像分手一样。

    • 可供电流*始终将文件流入 using 上面的样品确保清洁排放。
    • 合格入口*在添加之前,检查是否存在的文件. 提供清晰的路径日志。
  • ** 保持档案结构清洁**决定在档案中的一个根文件夹名称,并粘贴到它,如: app/package/.

  • 在目标平台上进行测试确保您的 7z 在您的用户依赖的工具中正确打开。

总结

您编程创建了一个 7z 存档,使用 Aspose.ZIP for .NET,从磁盘和内存添加了文件,保存了一个清洁的文件夹结构,并保存了结果。 .7z使用这些模式直接从您的 C# 应用程序发布、包装和出口。

More in this category