在 .NET 6 中,可以使用 System.IO.Compression.ZipFile 类来下载文件。以下是一个示例:

using System.IO.Compression;

public class Program
{
    public static void Main(string[] args)
    {
        string sourceFilePath = 'path/to/source/file.txt';
        string zipFilePath = 'path/to/destination/file.zip';

        // 压缩文件
        ZipFile.CreateFromDirectory(sourceFilePath, zipFilePath);

        // 下载文件
        using (var stream = File.OpenRead(zipFilePath))
        {
            var fileBytes = new byte[stream.Length];
            stream.Read(fileBytes, 0, fileBytes.Length);

            // 设置下载文件的响应头
            HttpContext.Current.Response.ContentType = 'application/zip';
            HttpContext.Current.Response.AddHeader('Content-Disposition', 'attachment; filename='file.zip'');
            HttpContext.Current.Response.BinaryWrite(fileBytes);
            HttpContext.Current.Response.End();
        }
    }
}

在上述示例中,首先使用 ZipFile.CreateFromDirectory 方法将指定的文件夹压缩成一个 zip 文件。然后,通过读取 zip 文件的内容并将其写入响应流中,设置下载文件的响应头,以便将压缩文件下载到客户端。

请注意,上述示例中的代码是在一个 ASP.NET 环境中使用的。如果您不在 ASP.NET 中使用,您可能需要根据您的应用程序类型进行相应的更改。

.NET 6 使用 ZipFile 下载文件 - 完整指南

原文地址: https://www.cveoy.top/t/topic/qkQp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录