如何解决如何并行观看约100个文件夹? FileSystemWatcher还是其他更有效的选择?
- 我在驱动器
Data
下有一个基本文件夹,在此下,我有大约 100 个文件夹。
-
在每个文件夹
Folder1.....100
中,第3部分应用程序之一推送zip文件(zip包含1个或多个文件)。 -
我必须编写一个窗口服务,它将监视所有100个文件夹中的文件到达。
-
一旦文件可用,我需要解压缩zip文件并将所有解压缩的文件放到第二个文件夹中,这需要在文件可用后立即对每个文件夹(文件夹1 .. 100)进行操作。 / p>
-
下面的代码建议我通过C#
FileSystemWatcher
,我可以一次查看一个文件夹并对此执行操作。
问题是,如何并行监视100个文件夹?
class ExampleAttributesChangedFiringTwice
{
public ExampleAttributesChangedFiringTwice(string demoFolderPath)
{
var watcher = new FileSystemWatcher()
{
Path = demoFolderPath,NotifyFilter = NotifyFilters.LastWrite,Filter = "*.txt"
};
watcher.Changed += OnChanged;
watcher.EnableRaisingEvents = true;
}
private static void OnChanged(object source,FileSystemEventArgs e)
{
// extract zip file,do the validation,copy file into other destination
}
}
目标文件夹,与zip的源文件夹无关,它是同一文件夹吗?也就是说,无论是从Folder1还是Folder2,都将被提取到FolderX?
所有“ C:\ ExtractedData”都使用目标文件夹。
那么将监视“数据”下的每个文件夹吗?没有“列入黑名单”文件夹?如果zip出现在Data本身而不是其子文件夹中怎么办?如果创建了一个新的子文件夹怎么办?
“ zip”始终位于“子文件夹”内,而不会在Data文件夹内创建。 是的,将来有机会,还会有更多子文件夹需要监视。
提取的文件是否基于其zip文件名进入目标文件夹中的单独子文件夹,或者只是将它们提取到目标文件夹中,例如,如果为A.zip,内容是否进入Target \ A或只是Target。
例如,如果A.zip包含2个文件“ 1.txt”和“ 2.txt”,则两个文件都将进入“ C:\ ExtractedData”。对于每个到达不同子文件夹的zip文件,这都是很常见的。
解决方法
“并行的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
}
}
如果跳过了一些文件,则可能一次创建的文件过多和/或压缩文件太大。 increase the buffer size或在new thread中启动它们。在具有繁忙IO或超大zip文件的HDD上,事件可能会超出存储功能,并且在长时间繁忙后会跳过文件,因此,您必须考虑写入不同的物理驱动器(而不仅仅是同一设备中的不同分区)代替。始终以您的预期使用方式进行验证。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。