美文网首页
.Net Core 跨平台压缩文件

.Net Core 跨平台压缩文件

作者: Rinaloving | 来源:发表于2022-03-20 16:05 被阅读0次

ZipFile

public string DownloadMaterial(dynamic data)
        {
            string url = null;

            try
            {
                MaterialPickData result = JsonConvert.DeserializeObject<MaterialPickData>(JsonConvert.SerializeObject(data));

                dynamic idArr = result?.idList;
                List<string> dList = JsonConvert.DeserializeObject<List<string>>(JsonConvert.SerializeObject(idArr));

                // 压缩文件
                //Data文件夹找到文件、移动到DownLoad文件夹的20xx时间戳文件夹下、打包该文件、删除原始文件夹
                List<string> fileNameList = new List<string>();
                dList?.ForEach(p =>
                {
                    string fileName = Get(p)?.SFile;
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        fileNameList.Add(fileName);
                    }
                });
                string filePath = $"{webRootPath}{Path.DirectorySeparatorChar}Data{Path.DirectorySeparatorChar}";
                string directoryName = string.Format("{0:yyyyMMddHHmmssfff}", DateTime.Now);
                string targetPath = $"{webRootPath}{Path.DirectorySeparatorChar}DownLoad{Path.DirectorySeparatorChar}{directoryName}{Path.DirectorySeparatorChar}";
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }
                fileNameList?.ForEach(f =>
                {

                    if (File.Exists($"{filePath}{f}"))
                    {
                        File.Copy($"{filePath}{f}", $"{targetPath}{f}");
                    }
                });

                //FileCompression.CompressDirectory(targetPath, $"{webRootPath}{Path.DirectorySeparatorChar}DownLoad{Path.DirectorySeparatorChar}{directoryName}.zip", 9, true);
                ZipFile.CreateFromDirectory(targetPath, $"{webRootPath}{Path.DirectorySeparatorChar}DownLoad{Path.DirectorySeparatorChar}{directoryName}.zip", CompressionLevel.Fastest, true);
                if (Directory.Exists($"{webRootPath}{Path.DirectorySeparatorChar}DownLoad{Path.DirectorySeparatorChar}{directoryName}"))
                {
                    Directory.Delete($"{webRootPath}{Path.DirectorySeparatorChar}DownLoad{Path.DirectorySeparatorChar}{directoryName}", true);
                }
                url = $"{directoryName}.zip";
            }
            catch (Exception ex)
            {
                url = "";
            }
            return url;

        }

相关文章

网友评论

      本文标题:.Net Core 跨平台压缩文件

      本文链接:https://www.haomeiwen.com/subject/yqfadrtx.html