简体   繁体   English

如何防止FolderBrowserDialog崩溃?

[英]How can I prevent FolderBrowserDialog to crash?

When the FolderBrowserDialog appears, and I press the close button or cancel button, it shows an error message. 当FolderBrowserDialog出现时,我按关闭按钮或取消按钮,它显示一条错误消息。 What do I need to do? 我需要做什么?

Thank you. 谢谢。

Here's my code. 这是我的代码。

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]);
}

As was mentioned you need to catch whether the dialog returns OK. 如前所述,您需要捕获对话框是否返回OK。 See if this helps: 看看这是否有帮助:

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]);
    }
}

The documentation for ShowDialog shows that it gives a result, telling you whether the user clicked OK. ShowDialog的文档显示它给出了结果,告诉您用户是否单击“确定”。 Your code is assuming the user always clicks OK, it's continuing regardless of the result. 您的代码假设用户始终单击“确定”,无论结果如何,它都将继续。 You need to check the return value, and only continue if it's DialogResult.OK . 您需要检查返回值,并且只有在返回DialogResult.OK才能继续。

If you do continue even though the user clicked Cancel or Close, several assumptions that should otherwise always be valid, may not hold. 如果即使用户单击“取消”或“关闭”,您仍然继续操作,否则本来应该一直有效的一些假设可能无法成立。 In particular, there is no path that the user has selected, because the user has not selected anything. 特别是,由于用户没有选择任何内容,因此没有用户选择的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM