如何在C#中限制文件对话框文件名中的特殊字符?



我的场景是,当OpenFileDialog中存在任何特殊字符(如#、%、+、-)时,需要限制对文件的选择。

我可以通过以下代码在选择文件后验证文件名。

Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
   if(dlg.SafeFileName.Contains("#") || dlg.SafeFileName.Contains("+")
   {
     // show error message;
     // Open file dialog again;   
   }
}

是否有任何方法可以在不关闭对话框的情况下验证文件名?

提前谢谢。

我不知道你在使用什么类型的FileDialog,但假设它是OpenFileDialog,你可以做一些事情。

OpenFileDialog dlg;
public Form1()
{
    InitializeComponent();
    dlg = new OpenFileDialog();
    dlg.FileOk += dlg_FileOk;
}
void dlg_FileOk(object sender, CancelEventArgs e)
{
    if (dlg.SafeFileName.Contains("#") || dlg.SafeFileName.Contains("+"))
    {
        e.Cancel = true;
        // show error message;
    }
}

您可以使用"FileOk"事件。当您在SaveFileDialogue中按"保存"时,会触发FileOk事件。然后你可以停止对话的结束。

这里有一个例子:

public void CallDialogue()
{
    var sfd = new SaveFileDialog();
    sfd.FileOk += ValidateName;
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        MessageBox.Show(sfd.FileName);
    }
}

private void ValidateName(object sender, CancelEventArgs e)
{
    var sfd = sender as SaveFileDialog;
    var file = new FileInfo(sfd.FileName);
    if (file.Name.Contains('#'))
        e.Cancel = true;
    // i did the FileInfo Stuff to quickly extract ONLY the file name, 
    // without the full path. Thats optional of course. Just an example ;-) 
}

为了便于说明,如果需要,还可以将验证内联:

using System;
using System.Windows.Forms;
namespace ConsoleApplication2
{
    class Program
    {
        [STAThread]
        private static void Main()
        {
            using (var dialog = new SaveFileDialog())
            {
                dialog.FileOk += (sender, args) =>
                {
                    var dlg = (FileDialog) sender;
                    if (dlg.FileName.IndexOfAny("+#%-".ToCharArray()) < 0)
                        return;
                    MessageBox.Show("Invalid character in filename: " + dlg.FileName);
                    args.Cancel = true;
                };
                dialog.ShowDialog();
            }
        }
    }
}

最新更新