“100个文件夹并行”的部分原来是一个红鲱鱼。因为所有新的zip文件无论在哪里显示都是一样的,所以只需添加
IncludeSubdirectories=true
够了。注意以下代码容易出现异常,请阅读注释
class WatchAndExtract
{
string inputPath, targetPath;
public WatchAndExtract(string inputPath, string targetPath)
{
this.inputPath = inputPath;
this.targetPath = targetPath;
var watcher = new FileSystemWatcher()
{
Path = inputPath,
NotifyFilter = NotifyFilters.FileName,
//add other filters if your 3rd party app don't immediately copy a new file, but instead create and write
Filter = "*.zip",
IncludeSubdirectories = true
};
watcher.Created += OnCreated; //use Changed if the file isn't immediately copied
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
//add filters if you're using Changed instead
//https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice
ZipFile.OpenRead(e.FullPath).ExtractToDirectory(targetPath);
//this will throw exception if the zip file is being written.
//Catch and add delay before retry, or watch for LastWrite event that already passed for a few seconds
}
}
如果它跳过了一些文件,则一次创建的文件太多和/或zip太大,无法处理。或者
increase the buffer size
或者让他们进来
new thread
. 在IO繁忙或zip文件非常大的HDD上,事件可能会超出存储容量,并且在长时间繁忙后会跳过文件,因此您必须考虑改为写入不同的物理驱动器(而不仅仅是同一设备中的不同分区)。始终验证预测的使用模式。