net 6 使用SystemIO和ZipFile实现文件打包下载
要使用System.IO和ZipFile来实现文件打包下载,首先需要引入两个命名空间:
using System.IO;
using System.IO.Compression;
然后,你可以使用以下代码来实现文件打包下载:
// 首先,将要打包的文件存储在一个列表中
List<string> filePaths = new List<string>
{
"file1.txt",
"file2.txt",
"file3.txt"
};
// 创建一个临时文件夹来存储打包后的文件
string tempFolder = Path.Combine(Path.GetTempPath(), "TempZipFolder");
Directory.CreateDirectory(tempFolder);
// 将文件复制到临时文件夹中
foreach (string filePath in filePaths)
{
string destPath = Path.Combine(tempFolder, Path.GetFileName(filePath));
File.Copy(filePath, destPath, true);
}
// 创建一个临时的压缩文件路径
string zipFilePath = Path.Combine(Path.GetTempPath(), "TempZipFile.zip");
// 使用ZipFile类来创建压缩文件
ZipFile.CreateFromDirectory(tempFolder, zipFilePath);
// 将压缩文件发送给用户进行下载
byte[] fileBytes = File.ReadAllBytes(zipFilePath);
string fileName = "Download.zip";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(fileBytes);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
response.Content.Headers.ContentLength = fileBytes.Length;
// 返回响应
return response;
上述代码中,首先创建一个临时文件夹来存储打包后的文件。然后,将要打包的文件复制到临时文件夹中。接下来,使用ZipFile类的CreateFromDirectory方法来创建压缩文件。最后,将压缩文件发送给用户进行下载。
请注意,上述示例中的文件路径和文件名仅作为示例,并且需要根据实际情况进行修改
原文地址: https://www.cveoy.top/t/topic/imdk 著作权归作者所有。请勿转载和采集!