【发布时间】:2021-01-29 06:42:44
【问题描述】:
我有一个创建 Zip 文件的函数,当文件数为几千时它工作得很好。但是,这在有时间限制的操作中并不是一个有效的解决方案。我想知道是否可以添加异步并发,以便最大限度地减少完成操作所需的总时间。
代码:
public static void CreateZip()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string dirRoot = @"C:\Dir\";
//get a list of files
string[] filesToZip = Directory.GetFiles(dirRoot, "*.*",
SearchOption.AllDirectories);
string zipFileName = @"C:\Dir.zip";
using (MemoryStream zipMS = new MemoryStream())
{
using (ZipArchive zipArchive = new ZipArchive(zipMS, ZipArchiveMode.Create,
true))
{
//loop through files to add
foreach (string fileToZip in filesToZip)
{
//read the file bytes
byte[] fileToZipBytes = System.IO.File.ReadAllBytes(fileToZip);
//create the entry - this is the zipped filename
//change slashes - now it's VALID
ZipArchiveEntry zipFileEntry = zipArchive.CreateEntry(
fileToZip.Replace(dirRoot, "").Replace('\\', '/'));
//add the file contents
using (Stream zipEntryStream = zipFileEntry.Open())
using (BinaryWriter zipFileBinary = new BinaryWriter(zipEntryStream))
{
zipFileBinary.Write(fileToZipBytes);
}
}
}
using (FileStream finalZipFileStream = new FileStream(zipFileName,
FileMode.Create))
{
zipMS.Seek(0, SeekOrigin.Begin);
zipMS.CopyTo(finalZipFileStream);
}
stopwatch.Stop();
Console.WriteLine("Total time elapsed: {0}",
stopwatch.ElapsedMilliseconds / 1000);
}
}
【问题讨论】:
-
什么样的应用程序?
-
为什么要先将 zip-archive 写入内存流,然后再写入实际文件?
标签: c# asynchronous async-await