Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# get the directory name from the DirectoryNotFoundException

Tags:

c#

exception

I made an application that search for some files in some directories. When a directory isn't there it throws the DirectoryNotFoundException. I catch that exception but it doesn't have a DirectoryName property or something like that like the FileNotFoundException (FileName). How can I find the Directory Name from the exception properties?

like image 936
Sp3ct3R Avatar asked Jun 23 '11 20:06

Sp3ct3R


2 Answers

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()); 
}   
like image 157
John Ruiz Avatar answered Sep 22 '22 21:09

John Ruiz


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("\".", ""));
}
like image 41
Pavel Morshenyuk Avatar answered Sep 21 '22 21:09

Pavel Morshenyuk