我需要一个自定义事件,如果在特定目录中发现/创建了一个新的/现有的文件,就会触发该事件。为了检查是否创建了新文件,我使用了SystemFileWatcher,它运行良好。为了检查程序启动时是否存在某些文件,我编写了一些代码并且也成功了。
我使用这个类作为事件参数:
public class FileDetectEventArgs : EventArgs
{
public String Source { get; set; }
public String Destination { get; set; }
public String FullName { get; set; }
public FileDetectEventArgs(String source, String destination, String fullName)
{
this.Source = source;
this.Destination = destination;
this.FullName = fullName;
}
}
如果SystemFileWatcher引发了FileCreated事件,我会使用以下代码行:
如果SystemFileWatcher引发了FileCreated事件,我会使用以下代码行:
public void onFileCreated(object sender, FileSystemEventArgs e)
{
// check if file exist
if (File.Exists(e.FullPath))
{
OnNewFileDetect(new FileDetectEventArgs(source, destination, e.FullPath));
}
}
如果文件存在,我会尝试以以下方式触发事件:
public void checkExistingFiles(String source, String filter)
{
DirectoryInfo di = new DirectoryInfo(source);
FileInfo[] fileInfos = di.GetFiles();
String fileFilter = filter.Substring(filter.LastIndexOf('.'));
foreach (FileInfo fi in fileInfos)
{
if (fi.Extension.Equals(fileFilter))
{
OnNewFileDetect(new FileDetectEventArgs(source, destination, fi.FullName));
}
}
}
这里是OnNewFileDetect事件:
protected void OnNewFileDetect(FileDetectEventArgs e)
{
if (OnNewFileDetectEvent != null)
{
OnNewFileDetectEvent(this, e);
}
}
问题在于,如果onFileCreated事件引发了我的OnNewFileDetect事件,一切都正常。但如果checkExistingFiles发现一些现有文件并尝试引发OnNewFileDetect事件,则什么也不会发生。我发现OnNewFileDetectEvent对象为空,因此什么也没发生。但是为什么当触发onFileCreated事件时它不为空呢?