protected virtual void EnsureDirectoryPermissions([NotNull] string path, [NotNull] IdentityReference identity) { Assert.ArgumentNotNull(path, "path"); Assert.ArgumentNotNull(identity, "identity"); DirectoryInfo dirInfo = new DirectoryInfo(path); DirectorySecurity dirSecurity = dirInfo.GetAccessControl(AccessControlSections.All); AuthorizationRuleCollection rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); if (!HasPermissions(rules, identity, FileSystemRights.FullControl)) { Log.Info("Granting full access for '{0}' identity to the '{1}' folder", identity, path, typeof(FileSystem)); FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); dirSecurity.AddAccessRule(rule); dirInfo.SetAccessControl(dirSecurity); dirSecurity = dirInfo.GetAccessControl(AccessControlSections.All); rules = dirSecurity.GetAccessRules(true, true, typeof(NTAccount)); Assert.IsTrue(HasPermissions(rules, identity, FileSystemRights.FullControl), "The Full Control access to the '" + path + "' folder isn't permitted for " + identity.Value + ". Please fix it and then restart the process"); } }
protected override void ProcessRecord() { bool isChange = false; DirectorySecurity security = Directory.GetAccessControl(DirectoryPath); // アクセス権を剥奪 if (All) { // テスト自動生成 _generator.DirectoryAccess(DirectoryPath, "", false); foreach (FileSystemAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount))) { security.RemoveAccessRule(rule); isChange = true; } } else if (!string.IsNullOrEmpty(Account)) { foreach (FileSystemAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount))) { string account = rule.IdentityReference.Value; // テスト自動生成 _generator.DirectoryAccount(DirectoryPath, account); if (Account.Contains("\\") && account.Equals(Account, StringComparison.OrdinalIgnoreCase) || !Account.Contains("\\") && account.EndsWith("\\" + Account, StringComparison.OrdinalIgnoreCase)) { security.RemoveAccessRule(rule); isChange = true; } } } if (isChange) { Directory.SetAccessControl(DirectoryPath, security); } // フォルダー属性を剥奪 if (!string.IsNullOrEmpty(_Attributes)) { // テスト自動生成 _generator.DirectoryAttributes(DirectoryPath, _Attributes, true); FileAttributes nowAttr = File.GetAttributes(DirectoryPath); FileAttributes delAttr = (FileAttributes)Enum.Parse(typeof(FileAttributes), _Attributes); File.SetAttributes(DirectoryPath, nowAttr & (~delAttr)); } WriteObject(new DirectorySummary(DirectoryPath, true)); }
/// <summary> /// Remove all user permissions from folder. /// </summary> /// If the user with name `username` exists, it will be preserved. /// <param name="fullPath">Full path to the folder on which to remove /// all user permissions.</param> /// <param name="username">Name of the user that will keep the /// permissions.</param> public static void RemovePermissionsForAllUsersButOne(string fullPath, string username) { // Is the function being run by an administrator? if (!LocalUserManager.IsAdministrator()) { // Inform const string msg = "This method must be run by an administrator."; sLogger.Error(msg); throw new InvalidOperationException(msg); } DirectoryInfo dirinfo = new DirectoryInfo(fullPath); DirectorySecurity dsec = dirinfo.GetAccessControl(AccessControlSections.All); AuthorizationRuleCollection rules = dsec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (AccessRule rule in rules) { if (rule.IdentityReference.Value != username) { dsec.PurgeAccessRules(rule.IdentityReference); dsec.ModifyAccessRule(AccessControlModification.RemoveAll, rule, out bool value); // Inform sLogger.Info("Removed permission from '" + fullPath + "' for '" + username + "'."); } } }
internal void PDrivePerms() { DirectorySecurity dsec = Directory.GetAccessControl(tCryptDriveName); AuthorizationRuleCollection rules = dsec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); //get existing rule and check to see if everyong full is set foreach (FileSystemAccessRule ace in rules) { if (ace.IdentityReference.Value == "Everyone" && ace.FileSystemRights == FileSystemRights.FullControl) { return; //Everyone full control already set } } try { SecurityIdentifier everyoneID = new SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); dsec.AddAccessRule(new FileSystemAccessRule(everyoneID, FileSystemRights.FullControl, AccessControlType.Allow)); dsec.AddAccessRule(new FileSystemAccessRule(everyoneID, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow)); Directory.SetAccessControl(tCryptDriveName, dsec); } catch (Exception e) { MessageBox.Show("Error changing the File permissions on the P Drive. The error is \r" + e.ToString()); } }
/// <summary> /// Removes all access rules from the supplied directory. /// </summary> /// <param name="path">The path to the directory to remove all access rules from.</param> /// <param name="security">The DirectorySecurity object of the directory that will be changed.</param> /// <param name="commitChanges">Indicates whether changes should be commited to this directory. Useful when combining multiple commands.</param> /// <returns>True if all rules were removed. False if an error occurred.</returns> static public bool RemoveAllAccessRules(string path, ref DirectorySecurity security, bool commitChanges) { // Check whether a path and security object were supplied. if (!string.IsNullOrEmpty(path) && security != null) { // A path and security object were supplied. // Check whether the path exists. if (SystemDirectory.Exists(path)) { // The directory exists. try { // Get all the authorization rules for the directory. AuthorizationRuleCollection ruleCollection = security.GetAccessRules(true, true, typeof(SecurityIdentifier)); // Remove all the authorization rules for the entry. foreach (FileSystemAccessRule rule in ruleCollection) { security.RemoveAccessRuleSpecific(rule); } // Commit the changes if necessary. if (commitChanges) { try { SystemDirectory.SetAccessControl(path, security); } catch (UnauthorizedAccessException) { // The current process does not have access to the directory specified by path. // Or the current process does not have sufficient privilege to set the ACL entry. return(false); } catch (PlatformNotSupportedException) { // The current operating system is not Windows 2000 or later. return(false); } } return(true); } catch { // There was an error removing the rules. return(false); } } else { // The directory does not exist. return(false); } } else { // An directory or security object were not supplied. return(false); } }
private FileSystemRights GetDirectoryRights(DirectorySecurity security, WindowsIdentity id) { FileSystemRights allowedRights = 0; FileSystemRights deniedRights = 0; foreach (FileSystemAccessRule rule in security.GetAccessRules(true, true, id.User.GetType())) { //If the identity associated with the rule //matches the user or any of their groups if (rule.IdentityReference.Equals(id) || id.Groups.Contains(rule.IdentityReference)) { uint right = (uint)rule.FileSystemRights & 0x00FFFFFF; //Filter out the generic rights so we get a //nice enumerated value if (rule.AccessControlType == AccessControlType.Allow) { allowedRights |= (FileSystemRights)(right); } else { deniedRights |= (FileSystemRights)(right); } } } return(allowedRights ^ deniedRights); }
private static void CheckFolderAccess(string folder, XElement xe) { if (Directory.Exists(folder) == false) { Console.WriteLine("EFS folder {0} does not exist", folder); } else { DirectoryInfo dInfo = new DirectoryInfo(folder); DirectorySecurity dSecurity = dInfo.GetAccessControl(); foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) { bool allowed = xe.Elements("NTAccount") .Where(x => x.Value.Equals(rule.IdentityReference.ToString(), StringComparison.CurrentCultureIgnoreCase)) .Any(); if (allowed == false) { Console.WriteLine("NTAccount {0} not in configured set for {1}", rule.IdentityReference.ToString(), folder); } } } }
public static void ExportToFile(string filename) { string path = @"C:\Users\praktyka\Desktop\AD"; string NtAccountName = @"Prolicht\praktyka"; DirectoryInfo di = new DirectoryInfo(path); DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All); AuthorizationRuleCollection 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)) { var filesystemAccessRule = (FileSystemAccessRule)rule; //Cast to a FileSystemAccessRule to check for access rights if ((filesystemAccessRule.FileSystemRights & FileSystemRights.WriteData) > 0 && filesystemAccessRule.AccessControlType != AccessControlType.Deny) { 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)); } } } Console.ReadLine(); }
/// <summary> /// Initializes WinCertes Directory path on the filesystem /// </summary> private static void InitWinCertesDirectoryPath() { _winCertesPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\WinCertes"; if (!System.IO.Directory.Exists(_winCertesPath)) { System.IO.Directory.CreateDirectory(_winCertesPath); } _certTmpPath = _winCertesPath + "\\CertsTmp"; if (!System.IO.Directory.Exists(_certTmpPath)) { System.IO.Directory.CreateDirectory(_certTmpPath); } // We fix the permissions for the certs temporary directory // so that no user can have access to it DirectoryInfo winCertesTmpDi = new DirectoryInfo(_certTmpPath); DirectoryInfo programDataDi = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)); DirectorySecurity programDataDs = programDataDi.GetAccessControl(AccessControlSections.All); DirectorySecurity winCertesTmpDs = winCertesTmpDi.GetAccessControl(AccessControlSections.All); winCertesTmpDs.SetAccessRuleProtection(true, false); foreach (FileSystemAccessRule accessRule in programDataDs.GetAccessRules(true, true, typeof(NTAccount))) { if (accessRule.IdentityReference.Value.IndexOf("Users", StringComparison.InvariantCultureIgnoreCase) < 0) { winCertesTmpDs.AddAccessRule(accessRule); } } winCertesTmpDi.SetAccessControl(winCertesTmpDs); }
public static bool checkIfInheritanceIsSet = false; //false= 5s:5s; true=9s:2s public static bool RemoveInheritance(string filePath, bool copyPermisions) { //return true; DirectoryInfo x = new DirectoryInfo(filePath); DirectorySecurity s = x.GetAccessControl(AccessControlSections.Owner | AccessControlSections.Group | AccessControlSections.Access); if (!checkIfInheritanceIsSet) { s.SetAccessRuleProtection(true, copyPermisions); x.SetAccessControl(s); return(true); } //only if checkIfInheritanceIsSet=true; SLOWER if (s.GetAccessRules(false, true, typeof(NTAccount)).Count > 0) { s.SetAccessRuleProtection(true, copyPermisions); x.SetAccessControl(s); return(true); } return(false); }
/// <summary> /// Determines whether this instance [can write file automatic folder] the specified path. /// </summary> /// <param name="path">The path.</param> /// <returns></returns> public static bool CanWriteFileToFolder(string path) { bool canWrite = false; string NtAccountName = @"MyDomain\MyUserOrGroup"; DirectoryInfo di = new DirectoryInfo(path); DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All); AuthorizationRuleCollection 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) { canWrite = true; } else { canWrite = false; } } } return(canWrite); }
//path içindeki dosya ve herşeyin kişilerini ve yetkilerini getiriyor private List <User> GetUserFilePermissionList(string path) { try { var userList = new List <User>(); DirectorySecurity dirSecurity = Directory.GetAccessControl(path); foreach (FileSystemAccessRule fileSystemAccessRule in dirSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) { userList.Add(new User { UserName = fileSystemAccessRule.IdentityReference.Value, Permission = fileSystemAccessRule.FileSystemRights.ToString(), Type = fileSystemAccessRule.AccessControlType.ToString() }); } if (userList.Count != 0) { return(userList); } return(null); } catch (Exception ex) { Console.Write(ex.Message); LogHelper.WriteLogException(ex.Message, ex.StackTrace); return(null); } }
public async Task <List <PermissionsModel> > GetPermissionAsync() { try { DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); AuthorizationRuleCollection acl = await Task.Run(() => dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))); foreach (FileSystemAccessRule ace in acl) { PermissionsModel Permodel = new PermissionsModel(); Permodel.IdentityReference = ace.IdentityReference.Value; Permodel.AccessControlType = ace.AccessControlType.ToString(); Permodel.FileSystemRights = FileSystemRightsCorrector(ace.FileSystemRights, false).ToString(); Permodel.IsInherited = ace.IsInherited; userPermission.Add(Permodel); } } catch (Exception ex) { throw ex; } return(userPermission); }
public static List <String> List(string Path) { List <String> list = new List <String>(); try { DirectoryInfo dInfo = new DirectoryInfo(Path); DirectorySecurity sec = dInfo.GetAccessControl(); foreach (FileSystemAccessRule rule in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) { string[] U = rule.IdentityReference.Value.Split('\\'); if (!list.Contains(U[U.Length - 1])) { list.Add(U[U.Length - 1]); } } } catch { } return(list); }
/// <summary> /// Return a list of all users who have any permissions on the folder. /// </summary> /// <param name="fullPath">Full path to the folder to query form users /// with permissions.</param> /// <returns>List of user names.</returns> public static List <string> GetUsersWithPermissions(string fullPath) { // Is the function being run by an administrator? if (!LocalUserManager.IsAdministrator()) { // Inform const string msg = "This method must be run by an administrator."; sLogger.Error(msg); throw new InvalidOperationException(msg); } // Initialize list of user names var userNames = new List <string>(); // Get directory security DirectoryInfo dirinfo = new DirectoryInfo(fullPath); DirectorySecurity dsec = dirinfo.GetAccessControl(AccessControlSections.All); // Extract user names AuthorizationRuleCollection rules = dsec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); foreach (AccessRule rule in rules) { userNames.Add(rule.IdentityReference.Value); } // Return the list of user names return(userNames); }
public void IntitializeSecurity() { DirectorySecurity security = Directory.GetAccessControl(BasePath); AuthorizationRuleCollection rules = security.GetAccessRules( true, false, typeof(SecurityIdentifier)); var q = from r in rules.OfType <FileSystemAccessRule>() where r.IdentityReference == AccountSid select r; if (q.Count() != 0) { // Remove any existing rules which could be allow or deny. q.ToList().ForEach(r => security.RemoveAccessRule(r)); } // BIND only requires modify (e.g. for process file and log). FileSystemAccessRule rule = new FileSystemAccessRule( AccountSid, FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); security.AddAccessRule(rule); Directory.SetAccessControl(BasePath, security); }
private static void Main() { Console.Write("Provide full directory path: "); _mentionedDir = Console.ReadLine(); try { if (_mentionedDir != null) { var directoryInfo = new DirectoryInfo(_mentionedDir); if (directoryInfo.Exists) { DirectorySecurity myDirSec = directoryInfo.GetAccessControl(); foreach (FileSystemAccessRule fileRule in myDirSec.GetAccessRules(true, true, typeof(NTAccount))) { Console.WriteLine("{0} {1} {2} access for {3}", _mentionedDir, fileRule.AccessControlType == AccessControlType.Allow ? "provides" : "denies", fileRule.FileSystemRights, fileRule.IdentityReference); } } } } catch { Console.WriteLine("Incorrect directory provided!"); } Console.ReadLine(); }
public static bool HasFolderWritePermission(string destDir) { if (string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) { return(false); } try { DirectorySecurity security = Directory.GetAccessControl(destDir); WindowsIdentity users = WindowsIdentity.GetCurrent(); foreach (AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier))) { if (users.User == rule.IdentityReference || users.Groups.Contains(rule.IdentityReference)) { FileSystemAccessRule rights = ((FileSystemAccessRule)rule); if (rights.AccessControlType == AccessControlType.Allow) { if (rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) { return(true); } } Console.WriteLine(rule.IdentityReference + ": " + rights.FileSystemRights); } Console.WriteLine(rule.IdentityReference); } return(false); } catch { return(false); } }
// List permissions of a file or directory. private void ListPermissions(string input, string currentDirectory, string tabs) { input = FileSystem.SanitizePath(input, currentDirectory); if (Directory.Exists(input)) { DirectoryInfo dInfo = new DirectoryInfo(input); DirectorySecurity dSecurity = dInfo.GetAccessControl(); AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); Console.WriteLine("Permissions of directory: " + input); foreach (FileSystemAccessRule ace in acl) { PermissionOut(ace, tabs); } } else { FileInfo dInfo = new FileInfo(input); FileSecurity dSecurity = dInfo.GetAccessControl(); AuthorizationRuleCollection acl = dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)); Console.WriteLine("Permissions of file: " + input); foreach (FileSystemAccessRule ace in acl) { PermissionOut(ace, tabs); } } }
//판자식 보호 상속삭제해제(타겟 문서의 폴더 경로 ) : 상속 삭제 public void panja_inherit_recover(string target_folder_dir) { DirectoryInfo dInfo = new DirectoryInfo(target_folder_dir); DirectorySecurity dSecurity = dInfo.GetAccessControl(); //디폴트 권한 클리어 AuthorizationRuleCollection rules = dSecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount)); foreach (FileSystemAccessRule rule in rules) { dSecurity.RemoveAccessRule(rule); } Directory.SetAccessControl(target_folder_dir, dSecurity); //상속 다시 추가 dSecurity.SetAccessRuleProtection(false, true); Directory.SetAccessControl(target_folder_dir, dSecurity); Directory.SetAccessControl(target_folder_dir, dSecurity); }
private static bool IsWritable(DirectoryInfo destDir) { if (string.IsNullOrEmpty(destDir.FullName) || !Directory.Exists(destDir.FullName)) { return(false); } try { DirectorySecurity security = Directory.GetAccessControl(destDir.FullName); SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); foreach (AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier))) { if (rule.IdentityReference == users) { FileSystemAccessRule rights = ((FileSystemAccessRule)rule); if (rights.AccessControlType == AccessControlType.Allow) { if (rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) { return(true); } } } } return(false); } catch { return(false); } }
public bool UserHasReadAccessToDirectory(DirectoryInfo directoryInfo) { try { DirectorySecurity dSecurity = directoryInfo.GetAccessControl(); AuthorizationRuleCollection authorizarionRuleCollecion = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)); foreach (FileSystemAccessRule fsAccessRules in authorizarionRuleCollecion) { if (_winId.UserClaims.Any(c => c.Value == fsAccessRules.IdentityReference.Value) && fsAccessRules.FileSystemRights.HasFlag(FileSystemRights.ReadData) && fsAccessRules.AccessControlType == AccessControlType.Allow) { return(true); } } return(false); } catch (UnauthorizedAccessException accessException) { Log.Information(accessException.Message); } catch (Exception ex) { Log.Error(ex, "Error in DirectoryData.UserHasReadAccessToDirectory - "); } return(false); }
/// <summary> /// Checks if access to the directory is granted. /// </summary> /// <param name="path">The path to the director as a <see cref="string" /></param> /// <returns> /// The <see cref="bool" /> true if the user has access, else false /// </returns> /// <remarks> /// Source: <see href="http://stackoverflow.com/questions/11709862/check-if-directory-is-accessible-in-c" /> /// </remarks> private static bool CanReadDirectory(string path) { bool readAllow = false; bool readDeny = false; DirectorySecurity accessControlList = Directory.GetAccessControl(path); if (accessControlList == null) { return(false); } AuthorizationRuleCollection accessRules = accessControlList.GetAccessRules(true, true, typeof(SecurityIdentifier)); foreach (FileSystemAccessRule rule in accessRules.Cast <FileSystemAccessRule>().Where(rule => (FileSystemRights.Read & rule.FileSystemRights) == FileSystemRights.Read)) { switch (rule.AccessControlType) { case AccessControlType.Allow: readAllow = true; break; case AccessControlType.Deny: readDeny = true; break; } } return(readAllow && !readDeny); }
//Check for Write Access to Directory public static bool CanWrite(string path) { try { bool writeAllow = false; bool writeDeny = false; DirectorySecurity accessControlList = Directory.GetAccessControl(path); AuthorizationRuleCollection accessRules = accessControlList?.GetAccessRules(true, true, typeof(SecurityIdentifier)); if (accessRules == null) { return(false); } foreach (FileSystemAccessRule rule in accessRules) { if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) { continue; } if (rule.AccessControlType == AccessControlType.Allow) { writeAllow = true; } else if (rule.AccessControlType == AccessControlType.Deny) { writeDeny = true; } } return(writeAllow && !writeDeny); } catch { return(false); } }
/// <summary> /// Resolve the path to the mm.cfg file /// </summary> public static String ResolveMMConfig() { String homePath = Environment.GetEnvironmentVariable("HOMEPATH"); String homeDrive = Environment.GetEnvironmentVariable("HOMEDRIVE"); if (!String.IsNullOrEmpty(homeDrive) && homePath != null) { try { String tempPath = homeDrive + homePath; DirectorySecurity security = Directory.GetAccessControl(tempPath); AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier)); WindowsIdentity currentUser = WindowsIdentity.GetCurrent(); foreach (FileSystemAccessRule rule in rules) { if (currentUser.User.Equals(rule.IdentityReference)) { if (rule.AccessControlType.Equals(AccessControlType.Allow)) { return(Path.Combine(tempPath, "mm.cfg")); } } } } catch {} // Not working... } String userProfile = Environment.GetEnvironmentVariable(Win32.IsRunningOnWindows() ? "USERPROFILE" : "HOME"); return(Path.Combine(userProfile, "mm.cfg")); }
public static Boolean ReadFolderPermission(DirectoryInfo di, string AccountName) { Boolean ergebnis; ergebnis = false; //DirectoryInfo di = new DirectoryInfo(path); DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All); AuthorizationRuleCollection 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(AccountName, StringComparison.CurrentCultureIgnoreCase)) { var filesystemAccessRule = (FileSystemAccessRule)rule; //Cast to a FileSystemAccessRule to check for access rights if ((filesystemAccessRule.FileSystemRights & FileSystemRights.WriteData) > 0 && filesystemAccessRule.AccessControlType != AccessControlType.Deny) { ergebnis = true; } else { ergebnis = false; } } } return(ergebnis); }
/// <summary> /// Recursively clears the permissions on the directory and enables permission inheritance. /// </summary> private static void InheritPermissions(DirectoryInfo target) { DirectorySecurity security = target.GetAccessControl(AccessControlSections.Access); security.SetAccessRuleProtection(false, false); foreach (AuthorizationRule rule in security.GetAccessRules(true, false, typeof(NTAccount))) { FileSystemAccessRule fsr = rule as FileSystemAccessRule; if (fsr != null) { security.RemoveAccessRule(fsr); } } target.SetAccessControl(security); foreach (DirectoryInfo directory in target.GetDirectories()) { InheritPermissions(directory); } foreach (FileInfo file in target.GetFiles()) { InheritPermissions(file); } }
/* Checks Folder Permissions */ public static bool CheckIfFolderPermissionIsSet(string path) { if (!DetectLinux.LinuxDetected()) { var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); DirectoryInfo Info = new DirectoryInfo(path); DirectorySecurity FolderSecurity = Info.GetAccessControl(); var acl = FolderSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)); bool IsPermsGood = false; foreach (FileSystemAccessRule rule in acl) { if (rule.IdentityReference.Value == everyone.Value && rule.AccessControlType == AccessControlType.Allow && (rule.FileSystemRights & FileSystemRights.Read) == FileSystemRights.Read) { IsPermsGood = true; } } Log.Info("FOLDER PERMISSION: [" + path + "] Is permission set? -> " + IsPermsGood); return(IsPermsGood); } else { return(true); } }
public void GetPermmssion(ClientContext context, Folder newFolder, string localrootfolder, string destinationLigraryTitle) { PermissionRepository Permission = new PermissionRepository(); string user; DirectorySecurity dSecurity = Directory.GetAccessControl(localrootfolder); /*--------------------------------------------- gets the users and their permissions---------------------------------*/ foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount))) { string[] splitRole = rule.FileSystemRights.ToString().Split(','); user = rule.IdentityReference.Value.Split(Convert.ToChar(92)).Last().ToString(); foreach (string s in splitRole) { DataTable MappedRoles = Permission.GetMappingRole(s); /*-------------gets the roletype equivalent of the permission*/ List <RoleType> MaproleList = new List <RoleType>(); foreach (DataRow row in MappedRoles.Rows) { foreach (RoleType value in Enum.GetValues(typeof(RoleType))) { /*-------------gets the roletype object of the permission*/ if (value.ToString() == row["RoleType"].ToString()) { MaproleList.Add(value); } } } if (MaproleList.Count > 0) { /*----------------- Assigns permissions of the folders-------------------------*/ AssignPermission(context, user, newFolder, MaproleList, destinationLigraryTitle); } } } }
static void Main(string[] args) { START: Console.Write("请输入文件夹的全路径:"); mentionedDir = Console.ReadLine(); try { DirectoryInfo myDir = new DirectoryInfo(mentionedDir); if (myDir.Exists) { DirectorySecurity dirSec = myDir.GetAccessControl(); foreach (FileSystemAccessRule fileRule in dirSec.GetAccessRules(true, true, typeof(NTAccount))) { Console.WriteLine(String.Format("{0} {1} {2} 访问 {3}", mentionedDir, fileRule.AccessControlType == AccessControlType.Allow ? "提供" : "拒绝", fileRule.FileSystemRights, fileRule.IdentityReference)); } } } catch (Exception e) { Console.WriteLine("错误的文件夹路径!"); Console.WriteLine(e.Message); goto START; } Console.ReadLine(); }