话不多说,直接上代码
public async Task<FileDto> Export_Zip(Export_ZipInput input)
{
var userid = 1;
var userName = "张三";
var file_zip = new FileDto(DateTime.Now.ToString("yyyyMMddHHmmssfff") + "-费用表" + ".zip", MimeTypeNames.ApplicationZip);//最后压缩的文件
var contents= _companyExpenseItemRepository.GetAll();
var streams = new Dictionary<string, Stream>();
var md5StreamList = new List<string>();
Stream streamWriter = null;
int i = 0;
foreach (var id in input.Ids)
{
i++;
var file = ExportCompanyExpenseDetails_Demo(id, 0, userName); //单个费用表的构造,此处不重复说明
//压缩
if (!streams.Any(p => p.Key == i.ToString() + "_" + file.FileName)) //为了防止名称重复,我给他加了一个编号
{
var filePath = Path.Combine(AppFolders.TempFileDownloadFolder, file.FileToken);
var newStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
var md5Stream = MD5Stream(newStream);
newStream.Close();
if (!md5StreamList.Exists(p => p == md5Stream))
{
streamWriter = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
streams.Add(i.ToString() + "_" + file.FileName, streamWriter);
md5StreamList.Add(md5Stream);
}
}
}
if (!streams.Any())
{
throw new UserFriendlyException("没有数据!");
}
MemoryStream ms = Compress.PackageManyZip(streams);
byte[] bytes = new byte[(int)ms.Length];
ms.Read(bytes, 0, bytes.Length);
ms.Close();
//创建一个文件流
FileStream fs = new FileStream(Path.Combine(AppFolders.TempFileDownloadFolder, file_zip.FileToken), FileMode.Create);
//将byte数组写入文件中
fs.Write(bytes, 0, bytes.Length);
//所有流类型都要关闭流,否则会出现内存泄露问题
foreach (var steam in streams)
{
steam.Value.Close();
}
fs.Close();
}
return file_zip;
}