Why is DirectoryNotFoundException not thrown?

  • Thread starter Thread starter Carl Johansson
  • Start date Start date
C

Carl Johansson

How come the DirectoryNotFoundException exception isn't thrown by the
following method?

private static void ShowSomeDirectoryInfo(string path)
{
// For some reason, exceptions are not thrown when the directory or
drive doesn't exist!?
DirectoryInfo dir = new DirectoryInfo(path);
Console.WriteLine("CreationTime: {0}", dir.CreationTime);
Console.WriteLine("Attributes: {0}", dir.Attributes);
}

OUTPUT:
Creation: 1601-01-01 01:00:00
Attributes: -1

Regards Carl Johansson
 
Peter said:
Good question. But, you'd have to ask the people who designed the
class. The behavior you're seeing is documented. You only get
DirectoryNotFoundException for paths that are _invalid_, rather than
those that aren't found.

Yes, it seems to me that they ought to be using a different exception.
But they aren't. Fortunately, you do have an "Exists" property you can
check as a work-around.

How would you create a directory, if the first line in

DirectoryInfo dir = new DirectoryInfo(@"C:\temp\somedir");
if (!dir.Exists)
dir.Create();

throws an exception?
 
Arto Viitanen said:
How would you create a directory, if the first line in

DirectoryInfo dir = new DirectoryInfo(@"C:\temp\somedir");
if (!dir.Exists)
dir.Create();

throws an exception?

Arto!

The DirectoryInfo constructor is not designed to throw a
DirectoryNotFoundException exception, and for a good reason, which I guess
is your point. How would we otherwise be able to create a directory that
doesn't exist!? Not caring about any other exceptions I would basically
create a new
directory the same way you do:

DirectoryInfo dir = new DirectoryInfo(@"Q:\Data\NewDir");
if (!dir.Exists)
try
{
dir.Create();
}
catch(DirectoryNotFoundException ex)
{
Console.WriteLine(ex.Message);
}


However, the DirectoryInfo.CreationTime property, for example, is indeed
defined to throw a DirectoryNotFoundException exception when, "The specified
path is invalid, such as being on an unmapped drive." Being unable to
provoke this exception made me write the question, thinking that perhaps
some compiler flag must be set or some additional code must be written to
include IO exceptions in a certain context.

Regards Carl Johansson
 
Pete!

Yes, you're right, the behaviour is documented! The "funny" thing is that
the documentation for the DirectoryNotFoundException exception for the
CreationTime Property also states: "The specified path is invalid, such as
being on an unmapped drive." But no matter what I do I can't provoke the
exception, and if I pass an _invalid_ path, an ArgumentException exception
is thrown already by the DirectoryInfo constructor. The practial approach in
any case, as you point out, is to get the value of the Exists property.
Anyway, as I stated to Arto, I thought perhaps I somehow manually needed to
activate IO exceptions to trigger.

Regards Carl Johansson
 
Back
Top