Reputation: 399
My scenario is, need to restrict the selection of file in an OpenFileDialog
, when there exists any special characters like #,%,+, -.
I can validate the file name after selecting file by the following code.
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
if(dlg.SafeFileName.Contains("#") || dlg.SafeFileName.Contains("+")
{
// show error message;
// Open file dialog again;
}
}
Is there any way to validate the file name without closing the dialog?
Thanks in advance.
Upvotes: 1
Views: 1691
Reputation: 109762
Just for illustration, you can also put the validation inline if you want:
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();
}
}
}
}
Upvotes: 2
Reputation: 1601
I dont't know what kind of FileDialog you are using but assuming it's an OpenFileDialog
, here's something you can do.
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;
}
}
Upvotes: 4
Reputation: 277
You can use the "FileOk" event. When you press "Save" in your SaveFileDialogue, the FileOk event is triggered. You can then stop the closing of the dialogue.
Here is an example:
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 ;-)
}
Upvotes: 4