【问题标题】:Create an error message for DirectoryNotFoundException in C# instead of crashing在 C# 中为 DirectoryNotFoundException 创建错误消息而不是崩溃
【发布时间】:2014-01-11 19:28:14
【问题描述】:

我有一个程序,它使用文件夹浏览器来定位文件,但在文件末尾添加了一些预先存在的文件夹。

例子:

System.IO.DirectoryInfo directoryName = new DirectoryInfo(@folderBrowser.SelectedPath + "/folder1/folder2/");

但是如果有人不使用 folderBrowser(他们应该有)并单击 Go 按钮,程序将崩溃并抛出异常。


所以我想做的是使用 MessageBox.Show 让用户知道他们没有在 folderBrowser 中选择一个文件夹,然后取消按钮按下以便他们可以选择一个文件夹。

【问题讨论】:

标签: c# exception-handling folderbrowserdialog


【解决方案1】:

只需使用try-catch statement

 try{

     System.IO.DirectoryInfo directoryName = new DirectoryInfo(@folderBrowser.SelectedPath + "/folder1/folder2/");
    }
    catch(DirectoryNotFoundException ex)  
    {
       MessageBox.Show("Folder not found")
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多