C#从DirectoryNotFoundException获取目录名称

| 我制作了一个在某些目录中搜索某些文件的应用程序。如果目录不存在,它将抛出“ 0”。我捕获到该异常,但是它没有
DirectoryName
属性或类似
FileNotFoundException
(FileName)之类的东西。如何从异常属性中找到目录名称?     
已邀请:
        无法自然地执行此操作。 将此类添加到您的项目中的某个位置:
public static class DirectoryNotFoundExceptionExtentions
{
    public static string GetPath(this DirectoryNotFoundException dnfe)
    {
        System.Text.RegularExpressions.Regex pathMatcher = new System.Text.RegularExpressions.Regex(@\"[^\']+\");
        return pathMatcher.Matches(dnfe.Message)[1].Value;
    }
}
捕获异常并使用如下类型的扩展名:
catch (DirectoryNotFoundException dnfe)
{
   Console.WriteLine(dnfe.GetPath()); 
}   
    
        它看起来像hack,但是您可以从
Message
属性中提取路径。对于我来说,我更喜欢使用
Directory.Exists
方法检查目录是否首先存在。
catch (DirectoryNotFoundException e)
{
    // Result will be: Could not find a part of the path \"C:\\incorrect\\path\".
    Console.WriteLine(e.Message);

    // Result will be: C:\\incorrect\\path
    Console.WriteLine(e.Message
        .Replace(\"Could not find a part of the path \\\"\", \"\")
        .Replace(\"\\\".\", \"\"));
}
    
        
FileNotFoundException
具有文件名,但是
DirectoryNotFoundException
没有目录名,不是吗? 解决方法:抛出异常之前,请使用Exception \ 10属性设置错误的目录名称。     
        在尝试在目录中查找文件之前,将目录名称保存在变量中。然后开始尝试查找该目录中的代码的块。现在,如果该代码块抛出,则目录名称可用。 例如:
// ... somewhere in some method that\'s about to search a directory.

var dirName = directories[i]; // or something -- how do you get it before you pass it to DirectoryInfo?

try
{
    SearchDirectory(dirName); // or a block of code that does the work
}
catch(Exception e)
{
    // at this point, you know dirName. You can log it, add it to a list of erroring
    // directories, or whatever. You could throw here, or swallow the error after logging it, etc.
}
    
        首先使用Directory.Exists检查它是否存在     
        如果您只想在IDE中消除这个错误,则可以尝试执行以下操作: 在Visual Studio中,转到
Debug -> Exceptions
,然后在
Thrown
框中选中
Common Language Runtime Exceptions
。发生异常时,这将使您直接进入异常状态,而不必等待被捕获。     
        对不起,我想找一个旧的帖子,但是正如其他人所说的那样,当FileNotFoundException确实将DirectoryNotFoundException设为属性时,DirectoryNotFoundException没有该目录是很愚蠢的。 我已将其作为.NET的功能请求: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/4472498-directorynotfoundexception-should-expose-the-name-     
        从大多数Directory类方法抛出的DirectoryNotFoundException的Message成员的格式为\“ Directory \'input \'not found。\”。从这个字符串中提取输入应该不难。 您的问题是,如果您是使用具有确切参数的方法来调用输入方法的,那么为什么需要从异常中获取输入参数?     

要回复问题请先登录注册