I'm using below code to give permission to a directory
static void SetPermission(string path)
{
if (Directory.Exists(path))
{
var directoryInfo = new DirectoryInfo(path);
// get the ACL of the directory
var directorySecurity = directoryInfo.GetAccessControl();
// remove inheritance, copying all entries so that they are direct ACEs
directorySecurity.SetAccessRuleProtection(true, true);
// do the operation on the directory
directoryInfo.SetAccessControl(directorySecurity);
// re-read the ACL
directorySecurity = directoryInfo.GetAccessControl();
// get the well known SID for "Users"
var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
// loop through every ACE in the ACL
foreach (FileSystemAccessRule rule in directorySecurity.GetAccessRules(true, false, typeof(SecurityIdentifier)))
{
// if the current entry is one with the identity of "Users", remove it
if (rule.IdentityReference == sid)
directorySecurity.RemoveAccessRule(rule);
}
var ntVirtaulUserName = #"NT Service\ServiceName";
// Add the FileSystemAccessRule to the security settings. give full control for user 'NT Service\ServiceName'
directorySecurity.AddAccessRule(new FileSystemAccessRule(ntVirtaulUserName.Replace(#".\", ""), FileSystemRights.FullControl, AccessControlType.Allow));
// do the operation on the directory
directoryInfo.SetAccessControl(directorySecurity);
}
}
This is working when giving permission to a directory (Test),
SetPermission(#"C:\Test");
Now I would like to give permission a file under the Test directory (log.txt), how to do that?
You can use FileInfo Class to handle permission on files. It's usage is like DirectoryInfo. Here is Microsoft document.
public static void AddFileSecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
FileInfo fInfo = new FileInfo(FileName);
FileSecurity fSecurity = fInfo.GetAccessControl();
fSecurity.AddAccessRule(newFileSystemAccessRule(Account,Rights,ControlType));
fInfo.SetAccessControl(fSecurity);
}
Is below code is fine?
var ntVirtaulUserName = #"NT Service\ServiceName";
// Get a FileSecurity object that represents the
// current security settings.
FileSecurity fSecurity = File.GetAccessControl(#"C:\Test\log.txt");
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(ntVirtaulUserName.Replace(#".\", ""), FileSystemRights.FullControl, AccessControlType.Allow));
// Set the new access settings.
File.SetAccessControl(#"C:\Test\log.txt", fSecurity);
Related
I want to grant full access / revoke access to network share folders (I could work with it as a mapped drive as well) using active directory admin account.
How can I File.GetAccessControl, .RemoveAccessRule and .AddAccessRule as active directory admin service account who is at the same time an admin of the network share folders?
Here is a snippet I used to do this.
private void EditAccess(List<string> userlist, string folder)
{
foreach (string user in userlist)
{
var AccessRule = new FileSystemAccessRule(user, FileSystemRights.FullControl,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow);
DirectoryInfo rootFolder = new DirectoryInfo(folder);
DirectorySecurity rootSec = rootFolder.GetAccessControl(AccessControlSections.Access);
bool Result;
rootSec.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);
InheritanceFlags iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
AccessRule = new FileSystemAccessRule(user, FileSystemRights.FullControl, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
rootSec.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);
rootFolder.SetAccessControl(rootSec);
}
}
I am trying to set program's installation folder permissions restricted only to Administrators.
There are two scenarios: the folder needs creation and folder already exists.
Here is my code:
public static void CreatePrivateFolder(string path)
{
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
DirectorySecurity securityRules = new DirectorySecurity();
FileSystemAccessRule fsRule =
new FileSystemAccessRule(sid, FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow);
securityRules.SetAccessRule(fsRule);
if (Directory.Exists(path))
{
Directory.SetAccessControl(path, securityRules);
}
else
{
Directory.CreateDirectory(path, securityRules);
}
}
When the folder needs creation, the CreateDirectory works fine, the folder's permissions restricted only to Administrators.
The strange thing is when I am re-run this code and flow to SetAccessControl - the folder's permissions being reset to regular folder with no restricted access.
What do I'm doing wrong?
Folder security results (for path c:\\folderCheck) :
Update
anrei solution answering my question.
However, it seem to be the same problem in a different way:
If the folder already exists with unrestricted permissions, anrei's code don't seem to be work.
The folder's permissions remain unrestricted.
Thanks!
Use this instead of your if (Directory.Exists(path)) block.
// what is
var existingACL = Directory.GetAccessControl(path);
// remove everything from what is
foreach (FileSystemAccessRule rule in existingACL.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
existingACL.RemoveAccessRuleAll(rule);
// add yours to what is
existingACL.AddAccessRule (fsRule);
// set again
Directory.SetAccessControl(path, existingACL);
I am creating a file like this:
System.IO.File.Create("file.dat").Close();
I want to set the file's permissions to disallow users from removing it. I tried the following, but it didn't work:
System.Security.AccessControl.FileSecurity fSecurity = File.GetAccessControl(dirPath + "\\" + fileName);
fSecurity.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Administrators",
System.Security.AccessControl.FileSystemRights.Delete, System.Security.AccessControl.AccessControlType.Allow));
File.SetAccessControl(dirPath + "\\" + fileName, fSecurity);
File permissions can be set using System.IO.File.SetAccessControl
See documentation and examples on MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx
To deny delete permissons to all users but administrators you can use this code
FileSecurity fSecurity = File.GetAccessControl(fileName);
AuthorizationRuleCollection rules = fSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
foreach (AuthorizationRule rule in rules)
{
System.Security.Principal.NTAccount account =
(System.Security.Principal.NTAccount)rule.IdentityReference.Translate(typeof(System.Security.Principal.NTAccount));
if (account.Value != "BUILTIN\\Administrators")
{
fSecurity.AddAccessRule(new FileSystemAccessRule(account.Value, FileSystemRights.Delete, AccessControlType.Deny));
}
}
File.SetAccessControl(fileName, fSecurity);
How we can use DirectorySecurity class for getting write access to a directory?
Method call:
// Add the access control entry to the directory.
AddDirectorySecurity(DirectoryName, #"MYDOMAIN\MyAccount", FileSystemRights.ReadData, AccessControlType.Allow);
Method definition:
// Adds an ACL entry on the specified directory for the specified account.
public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new DirectoryInfo object.
DirectoryInfo dInfo = new DirectoryInfo(FileName);
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity);
}
(Taken from MSDN)
I'm writing a DLL to change permissions on a folder and everything underneath the folder. Below is the code that I have right now.
The problem comes when I call addPermissions(). It's correctly setting the permissions on the dirName folder and any folder that I later create under dirName, but any folder that exists when I add permissions doesn't get the additional permissions.
Do I need to recursively set the permissions on all child folders? Or is there a way to do this with a line or two of code?
public class Permissions
{
public void addPermissions(string dirName, string username)
{
changePermissions(dirName, username, AccessControlType.Allow);
}
public void revokePermissions(string dirName, string username)
{
changePermissions(dirName, username, AccessControlType.Deny);
}
private void changePermissions(string dirName, string username, AccessControlType newPermission)
{
DirectoryInfo myDirectoryInfo = new DirectoryInfo(dirName);
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
string user = System.Environment.UserDomainName + "\\" + username;
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(
user,
FileSystemRights.Read | FileSystemRights.Write | FileSystemRights.ExecuteFile | FileSystemRights.Delete,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
newPermission
));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
}
This question is old but I was looking for the same thing and found a solution:
var dirInfo = new DirectoryInfo(dirName);
var dirSecurity = dirInfo.GetAccessControl();
// Add the DirectorySystemAccessRule to the security settings.
dirSecurity.AddAccessRule(new FileSystemAccessRule(
account,
rights,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow));
// Set the new access settings.
dirInfo.SetAccessControl(dirSecurity);
greetings
You have to do it recursively. You can specify inheritance rules for new folders/files but for existing you have to do it yourself.