2013-07-10 60 views

回答

8

你正確地做到了。使用Filter屬性可以將打開對話框中顯示的文件限制爲僅指定的類型。在這種情況下,用戶將在對話框中看到的唯一文件是擴展名爲.xml的文件。

但是,如果他們知道他們在做什麼,用戶繞過過濾器並選擇其他類型的文件是微不足道的。例如,他們只需輸入完整的名稱(如有必要,還可輸入路徑),或者輸入新的過濾器(例如*.*)並強制對話框向他們顯示所有這些文件。

因此,您仍然需要邏輯來檢查並確保所選文件符合您的要求。使用System.IO.Path.GetExtension方法從選定文件路徑獲取擴展名,然後對期望路徑進行序號不區分大小寫比較。

實施例:

OpenFileDialog ofd = new OpenFileDialog(); 
ofd.Filter = "XML Files (*.xml)|*.xml"; 
ofd.FilterIndex = 0; 
ofd.DefaultExt = "xml"; 
if (ofd.ShowDialog() == DialogResult.OK) 
{ 
    if (!String.Equals(Path.GetExtension(ofd.FileName), 
         ".xml", 
         StringComparison.OrdinalIgnoreCase)) 
    { 
     // Invalid file type selected; display an error. 
     MessageBox.Show("The type of the selected file is not supported by this application. You must select an XML file.", 
         "Invalid File Type", 
         MessageBoxButtons.OK, 
         MessageBoxIcon.Error); 

     // Optionally, force the user to select another file. 
     // ... 
    } 
    else 
    { 
     // The selected file is good; do something with it. 
     // ... 
    } 
}