Custom check file name on SaveFileDialog

I have SaveFileDialog


When the user clicks OK, I have to check if there is a similar filename.

The system ran a test like this, but I need to add a test. Is there a file with a similar name and numbering.

For example, if the user selected the file name "a" and there is a file "a1" or "a2", a warning message should appear. (as it appears when there is a file named "a").

Is there a way to do this?


source to share

2 answers


inherits a class FileDialog

that has an FileOk

event. You can put logic to check if similar files already exist in the handler method for this event. If the result true

, display a warning message. Then, if the user chooses No

from the alert dialog, set the parameter Cancel

to the parameter's CancelEventArgs

value true

, this will prevent the save file dialog from closing:

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", 
                      if(result == DialogResult.No)
                        args.Cancel = true;


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




this is the answer you want

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);
                ShowWarning = true;

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


ans Save()

method is save instructions ...



All Articles