从DirectoryNotFoundException中获取目录名称的C#方法

10

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


@Caimen:哪个目录不存在? - SLaks
1
你想知道它试图查找的名称吗? - Brandon Boone
@Caimen OP 的意思是异常应该“知道”检查了哪个目录(因为显然 FileNotFoundException 知道检查了哪个文件)。 - Michael Todd
5
你不是已经知道你在找的文件路径了吗?请确认一下。 - ChrisF
为什么你没有一个叫做 currentDirectory 的变量?如果找不到这个目录名,你可以从中获取名称。 - Tim Schmelter
显示剩余6条评论
8个回答

8

无法通过本地方式实现此操作。

在您的项目中添加此类:

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

在我的情况下,我必须寻找双引号:ex.Message.Split(new[] { '"', ''' })[1] - user1027167

5

看起来像是黑客攻击,但是你可以从 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("\".", ""));
}

根据http://msdn.microsoft.com/en-us/library/system.io.directorynotfoundexception.aspx的描述,路径似乎确实出现在“Message”属性中。 - BinaryTox1n
2
+1 - 我会称之为 hack,因为如果应用程序在不同的文化中运行,它将失败。但是,如果事先知道文化,则这将是一个好的解决方案。 (检查 Directory.Exists 是更糟糕的 hack,因为它可能在任何情况下失败,这意味着相同问题有两个不同的错误条件!) - Jeffrey L Whitledge
请记住,通常记录异常的正确方法不是使用其消息,而是调用 Exception.ToString(),其中包含消息和其他有用信息。 - Greg Jackson
2
你可以通过使用一个巨大的case语句来有条件地解析每个可能的文化/位置,将这个hack推广成一个更加史诗级别的hack。作为默认情况,只需抛出异常:throw new DirectoryNotFoundException("Could not find directory name in string \"" + e.Message + "\""); - Greg Jackson

2

在尝试查找目录中的文件之前,将目录名称保存在一个变量中。然后为查找该目录的代码开始一个try块。这样,如果该代码块抛出异常,您现在可以使用该目录名称。

例如:

// ... 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.
}

2

有点不一致的是,FileNotFoundException包含文件名,但是DirectoryNotFoundException没有包含目录名,是吧?

这里有一个解决方法:在抛出异常之前,使用异常的Data属性关联错误的目录名称。


1

首先使用Directory.Exists检查其是否存在


如果这个目录不在他的代码中怎么办?如果他是尝试使用该目录的人,那么他可能已经知道了目录名称,因此这一点在第一时间就是无意义的。 - Greg Jackson

1
如果您只是想在IDE中解决这个错误,那么可以尝试以下方法:
在Visual Studio中,转到“调试->异常”,然后勾选“Common Language Runtime Exceptions”的“Thrown”框。这将使您立即进入异常状态,而不必等待其被捕获。

1

0
大多数目录类方法抛出的DirectoryNotFoundException异常的Message成员的格式为“未找到目录'input'”。从这个字符串中提取input不应该很难。
然而,问题是,如果您是使用该确切参数调用方法的人,为什么需要从异常中获取输入参数呢?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接