marto31
marto31

Reputation: 21

Directory.Exist : identify types of errors

I use Directory.Exist to test a directory, but I can not distinguish types of errors.
I would like to distinguish if the directory doesn't exist or access is not allowed. I saw this link C# Test if user has write access to a folder but it's quite long and complicated. There is not an easier way?

Upvotes: 0

Views: 52

Answers (1)

Afzaal Ahmad Zeeshan
Afzaal Ahmad Zeeshan

Reputation: 15860

You can use the Exist method to check whether the directory exists or not. Like this

if(Directory.Exists(directory)) {
  // directory exists
  try
    {
      // and is accessible by user...
      File.GetAccessControl(filePath);
      return true;
    }
    catch (UnauthorizedAccessException)
    {
      // but is unable to be accessed...
      return false;
    }
} else {
  // directory doesn't exist, so no file accessible.
}

This is a bit easy and understand code for you. Each of the method is having its own commentary for you.

Upvotes: 1

Related Questions