如何防止FolderBrowserDialog崩溃?

时间:2013-12-12 07:01:10

标签: c#

当出现FolderBrowserDialog时,我按下关闭按钮或取消按钮,它会显示一条错误消息。我需要做什么?

谢谢。

这是我的代码。

private void openSlideShowFolder_Click(object sender, EventArgs e)
{
    folderBrowserDialog1.ShowDialog();
    string[] pics1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");
    string[] pics2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");
    string[] pics3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.bmp");
    folderFile = new string[pics1.Length + pics2.Length + pics3.Length];
    Array.Copy(pics1, 0, folderFile, 0, pics1.Length);
    Array.Copy(pics2, 0, folderFile, pics1.Length, pics2.Length);
    Array.Copy(pics3, 0, folderFile, pics1.Length + pics2.Length, pics3.Length);
    selected = 0;
    showImage(folderFile[selected]);
}

2 个答案:

答案 0 :(得分:2)

如上所述,您需要捕获对话框是否返回OK。看看这是否有帮助:

private void openSlideShowFolder_Click(object sender, EventArgs e)
{
    if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)
    {
    string[] pics1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");
    string[] pics2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");
    string[] pics3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.bmp");
    folderFile = new string[pics1.Length + pics2.Length + pics3.Length];
    Array.Copy(pics1, 0, folderFile, 0, pics1.Length);
    Array.Copy(pics2, 0, folderFile, pics1.Length, pics2.Length);
    Array.Copy(pics3, 0, folderFile, pics1.Length + pics2.Length, pics3.Length);
    selected = 0;
    showImage(folderFile[selected]);
    }
}

答案 1 :(得分:1)

ShowDialog的文档显示它会给出结果,告诉您用户是否单击了“确定”。您的代码假设用户始终单击“确定”,无论结果如何,都会继续。您需要检查返回值,并且只有在DialogResult.OK时才会继续。

如果即使用户单击“取消”或“关闭”仍然继续,则可能无法保留一些原本应该有效的假设。特别是,没有用户选择的路径,因为用户没有选择任何内容。