2012-01-05 106 views
0

我有一个程序,它有一个文件监视器,谁的路径是由用户输入(设置)。用户输入在文本框中输入路径,则单击按钮设置文件观察者的路径验证(检查)输入的路径

private void btnFileWatcherPath_Click(object sender, EventArgs e) 
{ 
    fileWatcher.Path = txtFileWatcherPath.Text; 
} 

文件观察者与另一个按钮打开(关闭按钮也是在程序)

private void btnFileOn_Click(object sender, EventArgs e) 
{ 
    fileWatcher.EnableRaisingEvents = true; 
    btnFileOn.Visible = false; 
    btnFileOff.Visible = true; 
} 

该方案的工作原理,但我没有验证的路径。输入的任何无效路径都会使程序崩溃。我怎样才能阻止这种(想一个标签,显示类似“无效的路径输入”)

+0

不够清楚,遗憾的是文件系统观察者。我正在查看整个目录,而不仅仅是一个文件。只是将File.Exist更改为Directory.Exist并完成了这项工作。欢呼家伙,谢谢你的快速回复。 – Dan1676 2012-01-05 16:53:51

回答

1

你可以只使用File.Exists

private void btnFileWatcherPath_Click(object sender, EventArgs e) 
{ 
    if(File.Exists(txtFileWatcherPath.Text)){ 
     fileWatcher.Path = txtFileWatcherPath.Text; 
    } 

} 
1

您可以使用File.Exists

if(File.Exists(path)){ 
    //Do some stuff 
} 
else{ 
    //It's bad man 
} 
0

验证架构,通过这些方法存在的路径:

string path = txtFileWatcherPath.Text; 

这(为目录):

System.IO.Directory.Exists(path); 

or this(for the actual file):

System.IO.File.Exists(path);