System.Windows.Forms.SaveFileDialog 不强制执行默认扩展名

发布于 2024-08-08 15:02:46 字数 1050 浏览 4 评论 0原文

我试图让 SaveFileDialogFileOpenDialog 对用户输入的文件名强制执行扩展名。我尝试使用 问题 389070< 中提出的示例/a> 但它无法按预期工作:

var dialog = new SaveFileDialog())

dialog.AddExtension = true;
dialog.DefaultExt = "foo";
dialog.Filter = "Foo Document (*.foo)|*.foo";

if (dialog.ShowDialog() == DialogResult.OK)
{
    ...
}

如果用户在恰好存在文件 test.xml 的文件夹中键入文本 test,对话框将建议名称 test.xml (而我实际上只想在列表中看到 *.foo)。更糟糕的是:如果用户选择 test.xml,那么我确实会得到 test.xml 作为输出文件名。

如何确保 SaveFileDialog 确实只允许用户选择 *.foo 文件?或者至少,当用户单击“保存”时,它会替换/添加扩展程序?

建议的解决方案(实现 FileOk 事件处理程序)仅完成部分工作,因为如果文件名的扩展名错误,我真的想禁用“保存”按钮。

为了留在对话框中更新FileOk处理程序中文本框中显示的文件名,以反映具有正确扩展名的新文件名,请参阅< href="https://stackoverflow.com/questions/1599511/how-to-replace-filename-in-savefiledialog-fileok-event-handler">以下相关问题。

I am trying to make SaveFileDialog and FileOpenDialog enforce an extension to the file name entered by the user. I've tried using the sample proposed in question 389070 but it does not work as intended:

var dialog = new SaveFileDialog())

dialog.AddExtension = true;
dialog.DefaultExt = "foo";
dialog.Filter = "Foo Document (*.foo)|*.foo";

if (dialog.ShowDialog() == DialogResult.OK)
{
    ...
}

If the user types the text test in a folder where a file test.xml happens to exist, the dialog will suggest the name test.xml (whereas I really only want to see *.foo in the list). Worse: if the user selects test.xml, then I will indeed get test.xml as the output file name.

How can I make sure that SaveFileDialog really only allows the user to select a *.foo file? Or at least, that it replaces/adds the extension when the user clicks Save?

The suggested solutions (implement the FileOk event handler) only do part of the job, as I really would like to disable the Save button if the file name has the wrong extension.

In order to stay in the dialog and update the file name displayed in the text box in the FileOk handler, to reflect the new file name with the right extension, see the following related question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

寄居人 2024-08-15 15:02:46

您可以处理 FileOk 事件,如果扩展名不正确则取消它

private saveFileDialog_FileOk(object sender, CancelEventArgs e)
{
    if (!saveFileDialog.FileName.EndsWith(".foo"))
    {
        MessageBox.Show("Please select a filename with the '.foo' extension");
        e.Cancel = true;
    }
}

You can handle the FileOk event, and cancel it if it's not the correct extension

private saveFileDialog_FileOk(object sender, CancelEventArgs e)
{
    if (!saveFileDialog.FileName.EndsWith(".foo"))
    {
        MessageBox.Show("Please select a filename with the '.foo' extension");
        e.Cancel = true;
    }
}
≈。彩虹 2024-08-15 15:02:46

AFAIK 没有可靠的方法来强制执行给定的文件扩展名。无论如何,最好在对话框关闭后验证扩展名是否正确,并在扩展名不匹配时通知用户他选择了无效文件。

AFAIK there's no reliable way to enforce a given file extension. It is a good practice anyway to verify the correct extension, once the dialog is closed and inform the user that he selected an invalid file if the extension doesn't match.

内心荒芜 2024-08-15 15:02:46

我最接近的方法是使用 FileOk 事件。例如:

dialog.FileOk += openFileDialog1_FileOk;

private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
  if(!dialog.FileName.EndsWith(".foo"))
  { 
     e.Cancel = true;
  }
}

查看 FileOK 事件在 MSDN 上。

The nearest I've got to this is by using the FileOk event. For example:

dialog.FileOk += openFileDialog1_FileOk;

private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
  if(!dialog.FileName.EndsWith(".foo"))
  { 
     e.Cancel = true;
  }
}

Checkout FileOK Event on MSDN.

喜爱纠缠 2024-08-15 15:02:46

我遇到了同样的问题,我可以通过执行以下操作来控制显示的内容:

使用 OpenFileDialog,过滤器字符串中的第一项是

openFileDialog1.Filter = "Program x Files (*.pxf)|*.pxf|txt files (*.txt)|*.txt";
openFileDialog1.ShowDialog();

SaveFileDialog 的默认值,过滤器中的第二项用作默认值:

SaveFileDialog saveFileDialog1 = new SaveFileDialog();

saveFileDialog1.Filter = "txt files (*.txt)|*.txt|Program x Files (*.pxf)|*.pxf";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    if (saveFileDialog1.FileName != null)
    {
        // User has typed in a filename and did not click cancel
        saveFile = saveFileDialog1.FileName;
        MessageBox.Show(saveFile);
        saveCurrentState();

    }
} 

将这两个过滤器与各自的文件对话框一起使用后,终于出现了预期的结果。默认情况下,当用户选择“保存”按钮并显示“保存文件”对话框时,所选文件类型是“保存文件”对话框的过滤器中定义的 Program X 文件类型。同样,为 openfiledialog 选择的文件类型是在 openfileDialog 的过滤器中定义的程序 X 文件类型。

正如本线程中上面提到的那样,最好进行一些输入验证。我只是想指出,两个对话框之间的过滤器似乎不同,即使它们都继承了 filedialog 类。

I ran into this same issue, and I was able to control what was shown by doing the following:

with the OpenFileDialog, the first item in the filter string was the default

openFileDialog1.Filter = "Program x Files (*.pxf)|*.pxf|txt files (*.txt)|*.txt";
openFileDialog1.ShowDialog();

with the SaveFileDialog, the second item in the filter was used as the default:

SaveFileDialog saveFileDialog1 = new SaveFileDialog();

saveFileDialog1.Filter = "txt files (*.txt)|*.txt|Program x Files (*.pxf)|*.pxf";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    if (saveFileDialog1.FileName != null)
    {
        // User has typed in a filename and did not click cancel
        saveFile = saveFileDialog1.FileName;
        MessageBox.Show(saveFile);
        saveCurrentState();

    }
} 

After having used these two filters with the respective fileDialogs, The expected results finally occurred. By default, when the user selects the save button and the savefiledialog shows up, the selected filetype is that of the Program X files type defined in the filter for the savefiledialog. Likewise the selected filetype for the openfiledialog is that of the Program X Files Type defined in the filter for the openfileDialog.

It would also be good to do some input validation as mentioned above in this thread. I just wanted to point out that the filters seem to be different between the two dialogs even though they both inherit the filedialog class.

_畞蕅 2024-08-15 15:02:46
    //this must be ran as administrator due to the change of a registry key, but it does work...

    private void doWork()
    {
        const string lm = "HKEY_LOCAL_MACHINE";
        const string subkey = "\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoComplete";
        const string keyName = lm + subkey;

        int result = (int)Microsoft.Win32.Registry.GetValue(keyName, "AutoComplete In File Dialog", -1);

        MessageBox.Show(result.ToString());

        if(result.ToString() == "-1")
        {
            //-1 means the key does not exist which means we must create one...
            Microsoft.Win32.Registry.SetValue(keyName, "AutoComplete In File Dialog", 0);
            OpenFileDialog ofd1 = new OpenFileDialog();
            ofd1.ShowDialog();
        }
        if (result == 0)
        {
            //The Registry value is already Created and set to '0' and we dont need to do anything
        }
    }
    //this must be ran as administrator due to the change of a registry key, but it does work...

    private void doWork()
    {
        const string lm = "HKEY_LOCAL_MACHINE";
        const string subkey = "\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\AutoComplete";
        const string keyName = lm + subkey;

        int result = (int)Microsoft.Win32.Registry.GetValue(keyName, "AutoComplete In File Dialog", -1);

        MessageBox.Show(result.ToString());

        if(result.ToString() == "-1")
        {
            //-1 means the key does not exist which means we must create one...
            Microsoft.Win32.Registry.SetValue(keyName, "AutoComplete In File Dialog", 0);
            OpenFileDialog ofd1 = new OpenFileDialog();
            ofd1.ShowDialog();
        }
        if (result == 0)
        {
            //The Registry value is already Created and set to '0' and we dont need to do anything
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文