我在文件夹上设置了filewatcher。每次创建一个子文件夹时,都会引发一个事件,我想继续这个事件并对该新文件夹中的文件做一些处理。问题是,有X个文件被复制/生成到新文件夹中,我不想执行剩下的代码,直到我知道在合理的时间内没有更多的新文件生成,假设30秒
以下是我尝试做的一些伪代码:
void fsw_Created(object sender, System.IO.FileSystemEventArgs e) //Event
handler for directory created
{
//Wait until no new file activity in the newly created for 30 secs
//Do stuff
}
答案 0 :(得分:0)
您可以使用包含 LastWriteTime 的 System.IO.DirectoryInfo 。
您可以按照以下方式使用它:
handler for directory created
{
string YourFolder = @"D:\CPT\Folder\"; // just en example
DirectoryInfo di1 = new DirectoryInfo(YourFolder);
DateTime dt1 = di1.LastWriteTime; // that is your base folder write time
Console.WriteLine(dt1);
Stopwatch sw = new Stopwatch(); //it's from System.Diagnostics
sw.Restart();
int secondWithoutAccess = 0;
do
{
if (sw.ElapsedMilliseconds > 1000)
{
//You must create new instance of Directory info every second
DirectoryInfo di2 = new DirectoryInfo(YourFolder);
DateTime dt2 = di2.LastWriteTime;
Console.WriteLine(dt2);
//if your base lastWriteTime is lower than
if (dt2 > dt1)
{
secondWithoutAccess = 0;
dt1 = dt2; // You must write last write time to proper compare
}
else secondWithoutAccess++;
sw.Restart(); // in all cases You restart timer
}
}
while (secondWithoutAccess < 30); // when 30 sec without access
Console.WriteLine("Files in folder didn't change for more than 30 sec");
// do rest of Your stuff here
}