1

I need to check if the current user has write permissions inside the path. Here an example:

string save_path = @"C:\Windows\somefolder";
string my_dir = Path.DirectorySeparatorChar + "foobar";

//check if specific path are valid
if (!Directory.Exists(save_path)) { return; }
if (Directory.Exists(save_path + my_dir)) { return; }

if (canWriteOnPath(save_path)) {
    Directory.CreateDirectory(save_path + my_dir);
} else {
    //You are not allowed to save here OR not are launching this application as "administrator"
    Directory.CreateDirectory(@"C:\Users\contoso\Documents\foobar");
}

solved in this question:

CurrentUserSecurity cus = new CurrentUserSecurity();
bool flag = cus.HasAccess(new DirectoryInfo(@"C:\Windows"), FileSystemRights.Write);

if (flag) {
    //yes create that folder
    Directory.CreateDirectory(Path.Combine(save_path, my_dir));
} else {
    //NO YOU CANT
    Directory.CreateDirectory(@"C:\Users\contoso\Documents\foobar");
}
Community
  • 1
  • 1
kapodamy
  • 65
  • 8

1 Answers1

2

The robust method would be to Try to create the directory and Catch any resulting exception.

The documentation for Directory.CreateDirectory lists the possible exceptions: IOException, UnauthorizedAccessException, ArgumentException, ArgumentNullException, PathTooLongException, DirectoryNotFoundException.

Although unlikely, it is possible that the permissions changed between your code checking that access is allowed and actually trying to create the directory.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Generating exceptions is more costly than just checking for access/existing folders. – Logarr Jan 28 '16 at 03:21
  • @Logarr The cost is incurred only if the exception is raised. If it goes wrong, an exception is going to be raised anyway, so it might as well be caught and dealt with cleanly rather than the program halting. All file I/O should be wrapped in a try..catch as it is one of those things that you can reasonably expect to go wrong. It is not like checking a divisor for zero before doing a division. – Andrew Morton Jan 28 '16 at 07:19