简体   繁体   English

C#-Microsoft.Win32.SaveFileDialog文件名问题

[英]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. 例如,如果将对话框的初始目录设置为“ C:\\ MainDir”,并且该目录由SubDir1,SubDir2组成,那么在保存文件对话框中,我可以看到我位于具有两个子目录的初始目录中。 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. 如果在对话框中将文件名设置为SubDir1(无扩展名),然后单击“保存”,则发生的是,不是将文件另存为“ filename.extension”,而是对话框打开了由文件名指定的目录。

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. 您不能覆盖Windows操作系统的默认保存方法。

What you can do is perhaps to verify whether the filename you wanted to use (in this instance, SubDir) exists already as a directory. 您可能要做的就是验证您要使用的文件名(在本例中为SubDir)是否已经作为目录存在。 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. 旁注:假设您有一个非常重要的文件夹,其中包含关键文件,而Windows将允许您保存以该目录命名的文件。 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. 在这里找到答案: 自定义OpenFileDialog可以帮助您解决问题。

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. 简而言之,我可能会三思而后行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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