Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating InitialDirectory for SaveFileDialog?

I'm opening a SaveFileDialog with an initial directory based on a user-defined path. I want make sure this path is valid before passing it in and opening the dialog. Right now I've got this:

Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();

if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory))
{
    dialog.InitialDirectory = initialDirectory;
}

bool? result = dialog.ShowDialog();

However, it seems \ is slipping by and causing a crash when I call ShowDialog. Are there other values that could cause crashes? What rules does the InitialDirectory property need to follow?

like image 717
RandomEngy Avatar asked Oct 23 '25 16:10

RandomEngy


1 Answers

The quick and easy way to fix it would be to get the full path:

dialog.InitialDirectory = Path.GetFullPath(initialDirectory);

This will expand relative paths to the absolute ones that the SaveFileDialog expects. This will expand just about anything that resembles a path into a full, rooted path. This includes things like "/" (turns into the root of whatever drive the current folder is set to) and "" (turns into the current folder).

like image 99
Mike Caron Avatar answered Oct 26 '25 05:10

Mike Caron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!