2012-01-05 74 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);