2014-09-21 15 views
3

我有一個SaveFileDialog在SaveFileDialog上自定義檢查文件名

當用戶點擊確定,我必須檢查是否有類似的文件名。

系統一直在做這樣的測試,但我需要添加一個測試是否有一個具有相似名稱和編號的文件。

例如,如果用戶選擇文件名「a」並且存在文件「a1」或「a2」,則應該出現警告消息。 (因爲它存在一個名爲「a」的文件)。

有沒有辦法做到這一點?

+0

不要在這種情況下使用SaveFileDialog。使用自己創建的控件爲此創建一個自定義邏輯。 – 2014-09-21 04:57:32

+0

* a *&* a1 *&* a2 *位於相同路徑中? – 2014-09-21 05:11:15

+0

@MehdiKhademloo,是的。 – 2014-09-21 05:13:28

回答

2

SaveFileDialog繼承FileDialog類其中有FileOk事件。您可以將邏輯檢查此事件的處理程序方法中是否已存在類似的文件。如果結果是true,則顯示警告消息。然後,如果用戶從警告對話框選擇NoCancelEventArgs參數的Cancel屬性設置爲True,這將阻止關閉保存文件對話框窗口:

var dlg = new SaveFileDialog(); 
dlg.FileOk += (o, args) => 
       { 
        var file = dlg.FileName; 
        if (isSimilarFileExist(file)) 
        { 
         var result = MessageBox.Show("Similar file names exist in the same folder. Do you want to continue?", 
                "Some dialog title", 
                MessageBoxButtons.YesNo, 
                MessageBoxIcon.Warning 
               ); 
         if(result == DialogResult.No) 
         args.Cancel = true; 
        } 
       }; 
dlg.ShowDialog(); 

...... 

private bool isSimilarFileExist(string file) 
{ 
    //put your logic here 
} 
0

這就是答案你想

SaveFileDialog S = new SaveFileDialog(); 
if(S.ShowDialog() == DialogResult.OK) 
{ 
    bool ShowWarning = false; 
    string DirPath = System.IO.Path.GetDirectoryName(S.FileName); 
    string[] Files = System.IO.Directory.GetFiles(DirPath); 
    string NOFWE = DirPath+"\\"+System.IO.Path.GetFileNameWithoutExtension(S.FileName); 
    foreach (var item in Files) 
    { 

     if (item.Length > NOFWE.Length && item.Substring(0, NOFWE.Length) == NOFWE) 
     { 
      int n; 
      string Extension = System.IO.Path.GetExtension(item); 
      string RemainString = item.Substring(NOFWE.Length, item.Length - Extension.Length - NOFWE.Length); 
      bool isNumeric = int.TryParse(RemainString, out n); 
      if(isNumeric) 
      { 
       ShowWarning = true; 
       break; 
      } 

     } 
    } 
    if(ShowWarning) 
    { 
     if (MessageBox.Show("Warning alert!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) 
      Save();//Saving instance 
    } 
    else 
    { 
     Save();//Saving instance 
    } 
} 

ANS Save()方法是保存說明...