Just have been playing on my lunch and wondered how can
I detect from my C# code whether I have access right for reading/writing to
specific folder.
I come up after bit of trial and error to code as follows:
string path = @"c:\temp"; string NtAccountName = @"group\userName"; var di = new DirectoryInfo(path); var acl = di.GetAccessControl(AccessControlSections.Access); var rules = acl.GetAccessRules(true, true, typeof(NTAccount)); //Go through the rules returned from the DirectorySecurity foreach (AuthorizationRule rule in rules) { //If we find one that matches the identity we are looking for if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase)) { //Cast to a FileSystemAccessRule to check for access rights if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0) { Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path)); } else { Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path)); } if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.Read) > 0) { Console.WriteLine(string.Format("{0} does not have read access to {1}", NtAccountName, path)); } else { Console.WriteLine(string.Format("{0} does not have read access to {1}", NtAccountName, path)); } } }
original code that i used is of course from StackOverflow
No comments:
Post a Comment