C# get the directory name from the DirectoryNotFoundException

There's no way to natively do this.

Add this class somewhere to your project:

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 the exception and use the type extension like this:

catch (DirectoryNotFoundException dnfe)
{
   Console.WriteLine(dnfe.GetPath()); 
}   

It looks like a hack, but you can extract the path from the Message property. As for me, I would prefer to check if the directory exists first, by using the Directory.Exists method.

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("\".", ""));
}

It is a little inconsistent that FileNotFoundException has the file name, but DirectoryNotFoundException doesn't have the directory name, isn't it?

Here's a work around: Before you throw the exception, associate the errant directory name using Exception's Data property.

Tags:

C#

Exception