C#从DirectoryNotFoundException获取目录名

Sp3*_*t3R 8 c# exception

我创建了一个在某些目录中搜索某些文件的应用程序.当一个目录不存在时,它会抛出DirectoryNotFoundException.我捕获了该异常,但它没有DirectoryName属性或像FileNotFoundException(FileName)那样的东西.如何从例外属性中找到目录名称?

Joh*_*uiz 6

没有办法原生这样做.

将此类添加到项目的某个位置:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

捕获异常并使用类似扩展名,如下所示:

catch (DirectoryNotFoundException dnfe)
{
   Console.WriteLine(dnfe.GetPath()); 
}   
Run Code Online (Sandbox Code Playgroud)


Pav*_*yuk 5

看起来很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("\".", ""));
}
Run Code Online (Sandbox Code Playgroud)

  • +1-我称其为hack,因为如果应用程序以其他区域性运行,它将失败。但是,对于任何事先已知该文化的场合,这都是一个很好的解决方案。(检查Directory.Exists是更糟糕的黑客,因为在任何情况下都可能失败,这意味着同一问题有两种不同的错误情况!) (2认同)
  • 您可以通过使用巨大的case语句有条件地解析每种可能的文化/地理位置,将黑客归纳为更具史诗性的黑客。作为默认情况,只需抛出一个异常:`throw new DirectoryNotFoundException(“在字符串\”“ + e.Message +” \“”)中找不到目录名称。 (2认同)