Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 5th, 2012  |  syntax: None  |  size: 1.15 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. UnauthorizedAccessException when accessing a directory I just created
  2. if (!Directory.Exists(dirPath))
  3.         Directory.CreateDirectory(dirPath);
  4.     var a = HasWritePermissionOnDir(dirPath); <- This is only here to see if the value is true and it is.
  5.     tw = new StreamWriter(dirPath);
  6.  
  7.     public static bool HasWritePermissionOnDir(string path)
  8.     {
  9.         var writeAllow = false;
  10.         var writeDeny = false;
  11.         var accessControlList = Directory.GetAccessControl(path);
  12.         if (accessControlList == null)
  13.             return false;
  14.         var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
  15.         if (accessRules == null)
  16.             return false;
  17.  
  18.         foreach (FileSystemAccessRule rule in accessRules)
  19.         {
  20.             if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue;
  21.  
  22.             if (rule.AccessControlType == AccessControlType.Allow)
  23.                 writeAllow = true;
  24.             else if (rule.AccessControlType == AccessControlType.Deny)
  25.                 writeDeny = true;
  26.         }
  27.  
  28.         return writeAllow && !writeDeny;
  29.     }