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?
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("\".", ""));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With