简体   繁体   中英

C# - Microsoft.Win32.SaveFileDialog Filename Issue

I have a problem where if you set the filename in the dialog box to a sub directory within the initial directory you set it to and then clicking 'Save', the dialog window doesn't actually save the file but opens the sub directory which I could still interact with.

For example If I set the initial directory for the dialog to 'C:\\MainDir' and that directory consists of SubDir1, SubDir2, then in the save file dialog I could see that I am in the initial directory with two sub directories. If I set the filename to SubDir1 (no extension) in the dialog, and then I hit 'Save', what happens is instead of saving the file as 'filename.extension' the dialog opens the directory specified by the file name.

Here's what I currently have:

SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = ext;
dlg.AddExtension = true;
dlg.FileName = filename;
dlg.Filter = filter;
dlg.FileOk += OnFileDialogOk;
dlg.InitialDirectory = dir;
bool? dlgRes = dlg.ShowDialog();

Is this something that can be easily fixed?

Quick Answer: No.

You cannot override the default save method of Windows OS.

What you can do is perhaps to verify whether the filename you wanted to use (in this instance, SubDir) exists already as a directory. If it does, then you would need to change that name, as that will only manifest the behavior you've already seen.

Side Note: Just imagine you have a very important folder which contains critical files, and Windows would let you save a file that is named with that directory. That is a disaster waiting to happen.

The only ways I can think of doing this are a bit extreme:

  • You could roll your own dialog
  • You could modify the functionality of the standard dialog

The answers found here: Customizing OpenFileDialog could help with that.

I guess I should also note that while it may seem helpful to accommodate this kind of input and automatically append the extension, it'll be counter-intuitive to many users who will expect the default behaviour.

In short, I'd probably think twice about this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM