如果选择的VistaFolderBrowserDialog不存在,可以自动创建文件夹吗?

时间:2013-09-17 17:33:22

标签: c# .net

我使用Ookii.Dialog

当我使用VistaFolderBrowserDialog选择一个文件夹时,我希望如果所选文件夹不存在,它会要求创建它而不是警告该文件夹不存在。

我该怎么办呢?是否有任何活动或选择?

这是我的代码。

VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
dialog.Description = "Select Export Folder:";
dialog.ShowNewFolderButton = true;
dialog.SelectedPath = Path.Combine(Path.GetDirectoryName(lastSelectPath), 
       Path.GetFileNameWithoutExtension(lastAppendFilepath));

1 个答案:

答案 0 :(得分:0)

您需要做的就是检查目录是否与Directory.Exists(string)一致,通过MessageBox询问用户,然后使用Directory.CreateDirectory(string)创建目录。

var initialDirectory = Path.Combine(Path.GetDirectoryName(lastSelectPath), 
       Path.GetFileNameWithoutExtension(lastAppendFilepath));

if(!Directory.Exists(initalDirectory))
{
    if(MessageBox.Show("Folder does not exist", "The default folder does not exist, create it?", MessageBoxButtons.YesNo) == DialogResult.Yes)
        Directory.CreateDirectory(initalDirectory);
}

VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
dialog.Description = "Select Export Folder:";
dialog.ShowNewFolderButton = true;
dialog.SelectedPath = initalDirectory;

请注意,Directory.CreateDirectory(initalDirectory)可能会引发异常。例如,您尝试创建一个您无权创建目录的目录。您可能希望将两行包装在try-catch块中并适当地处理任何错误。