我创建了一个在某些目录中搜索某些文件的应用程序.当一个目录不存在时,它会抛出DirectoryNotFoundException.我捕获了该异常,但它没有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;
}
}
Run Code Online (Sandbox Code Playgroud)
捕获异常并使用类似扩展名,如下所示:
catch (DirectoryNotFoundException dnfe)
{
Console.WriteLine(dnfe.GetPath());
}
Run Code Online (Sandbox Code Playgroud)
看起来很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)