3

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?

4

1 回答 1

7

修复它的快速简便的方法是获取完整路径:

dialog.InitialDirectory = Path.GetFullPath(initialDirectory);

这会将相对路径扩展到SaveFileDialog期望的绝对路径。这会将任何类似于路径的东西扩展为完整的、有根的路径。这包括诸如“/”(变成当前文件夹设置到的任何驱动器的根目录)和“”(变成当前文件夹)之类的东西。

于 2011-02-26T22:51:52.143 回答