"使用 .NET 6 和 System.IO.Compression 命名空间中的 ZipArchive 类,你可以轻松打包整个文件夹并进行下载。\n\n步骤\n\n1. 创建 FileController 类: 创建一个新的控制器,例如 FileController,用于处理文件打包和下载操作。\n2. 添加 DownloadFolder 方法: 在控制器中添加一个名为 DownloadFolder 的方法,该方法负责打包文件夹并生成可下载的 ZIP 文件。\n3. 指定文件夹路径和压缩文件路径: 在方法中指定要打包的文件夹路径和压缩文件的保存路径。\n4. 创建压缩文件: 使用 ZipFile.Open 方法创建一个新的 ZipArchive 对象,并指定压缩文件的保存路径。\n5. 遍历文件夹中的所有文件和子文件夹: 使用 Directory.GetFiles 方法遍历文件夹中的所有文件和子文件夹,并使用 ZipArchive.CreateEntryFromFile 方法将它们添加到压缩文件中。\n6. 获取相对路径: 为了保证压缩文件中的文件结构和原始文件夹相同,需要使用 GetRelativePath 方法获取文件相对于原始文件夹的相对路径。\n7. 下载压缩文件: 使用 File.ReadAllBytes 方法读取压缩文件内容,并使用 File 方法将其作为响应返回给客户端。\n8. 删除临时压缩文件: 为了避免磁盘空间占用,在方法执行完毕后删除临时压缩文件。\n\n代码示例\n\ncsharp\nusing System;\nusing System.IO;\nusing System.IO.Compression;\nusing System.Net;\nusing Microsoft.AspNetCore.Mvc;\n\npublic class FileController : ControllerBase\n{\n [HttpGet]\n public IActionResult DownloadFolder()\n {\n string folderPath = \"C:\\Path\\To\\Folder\"; // 指定要打包的文件夹路径\n\n string zipPath = \"C:\\Path\\To\\Folder.zip\"; // 指定压缩文件的保存路径\n\n try\n {\n // 创建一个新的压缩文件\n using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Create))\n {\n // 遍历文件夹中的所有文件和子文件夹\n foreach (string filePath in Directory.GetFiles(folderPath, \"*\", SearchOption.AllDirectories))\n {\n // 将文件添加到压缩文件中\n zipArchive.CreateEntryFromFile(filePath, GetRelativePath(filePath, folderPath));\n }\n }\n\n // 从本地下载压缩文件\n byte[] fileBytes = System.IO.File.ReadAllBytes(zipPath);\n return File(fileBytes, \"application/zip\", \"Folder.zip\");\n }\n catch (Exception ex)\n {\n // 处理异常\n return BadRequest(ex.Message);\n }\n finally\n {\n // 删除临时的压缩文件\n System.IO.File.Delete(zipPath);\n }\n }\n\n // 获取相对路径\n private string GetRelativePath(string fullPath, string basePath)\n {\n if (!basePath.EndsWith(Path.DirectorySeparatorChar.ToString()))\n {\n basePath += Path.DirectorySeparatorChar;\n }\n\n Uri baseUri = new Uri(basePath);\n Uri fullUri = new Uri(fullPath);\n\n return Uri.UnescapeDataString(baseUri.MakeRelativeUri(fullUri).ToString());\n }\n}\n\n\n注意\n\n* 示例代码中的文件路径和保存路径是用于演示目的,你需要根据自己的实际情况进行更改。\n* 为了确保代码安全可靠,请添加适当的异常处理和错误处理机制。\n* 为了提升用户体验,可以使用进度条或其他方式展示打包进度。\n* 为了避免磁盘空间占用,可以考虑使用内存流来存储压缩文件内容,并直接将其作为响应返回给客户端。\n\n相关资源\n\n* System.IO.Compression 命名空间\n* ZipArchive 类\n* Directory.GetFiles 方法\n* File.ReadAllBytes 方法\n* File 方法\n\n通过以上步骤和代码示例,你可以轻松地在 .NET 6 中实现文件夹打包下载功能,为用户提供更加便捷的文件管理体验。\n


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

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