2016-03-20 26 views
1

我无法理解FileSystemWatcher应该如何工作。我试图让我的代码等待文件存在,然后调用另一个函数。我的代码如下:FileSystemWatcher ArgumentException

string path2 = @“N:\ reuther \ TimeCheck \ cavmsbayss.log”;

 FileSystemWatcher fw = new FileSystemWatcher(path2); 
     fw.Created += fileSystemWatcher_Created; 

然后我有应处理的文件,一旦它的事件被称为一个独立的功能:

 static void fileSystemWatcher_Created(object sender, FileSystemEventArgs e) 
    { 
     MessageBox.Show("Ok im here now"); 
    } 

目录名N:\鲁瑟\ TimeCheck \ cavmsbayss .log无效。

+0

你可以看一个目录,而不是一个文件。 [MSDN](https://msdn.microsoft.com/en-us/library/b36854c3(v = vs.110).aspx) –

+0

是否没有办法让它监视要创建的文件? –

+0

一旦'Created'事件触发,应该是。 –

回答

3

根据该docs,所述path参数表示:

的目录进行监控,在标准或通用命名约定(UNC)表示法。

它传递的目录路径,而不是特定的文件:

string pathToMonitor = @"N:\reuther\TimeCheck"; 
FileSystemWatcher fw = new FileSystemWatcher(pathToMonitor); 
fw.EnableRaisingEvents = true; // the default is false, you may have to set this too 
fw.Created += fileSystemWatcher_Created; 

然后,只需注意创建该文件,在FileSystemEventArgs类使用无论是NameFullPath属性:

static void fileSystemWatcher_Created(object sender, FileSystemEventArgs e) 
{ 
    if (e.Name == "cavmsbayss.log") 
    { 
     MessageBox.Show("Ok im here now"); 
    } 
} 
+0

我遇到了该代码的问题...我尝试使用它: string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string path2 = desktopPath + @“\”+ @“RaidTimestamps \”; FileSystemWatcher fw = new FileSystemWatcher(path2); fw.Created + = fileSystemWatcher_Created; static void fileSystemWatcher_Created(object sender,FileSystemEventArgs e) { MessageBox.Show(e.Name); (e.Name ==“orvmsnw1ss.log”) { MessageBox.Show(“Ok im here now”); } } –

+0

以上,根本没有任何显示。即使我知道路径是100%正确的,但意味着代码不会执行。 –

+0

尝试在'fileSystemWatcher_Created'方法的第一行放置一个断点。它受到打击吗?检查“e.Name”和“e.FullName”的值以确保它们符合您的期望。 –