Changing permissions on child folders in C# - c#

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.

Related

how to give permission to file rather than directory

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);

c# Grant user access to network folder using ad service account

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);
}
}

Directory.SetAccessControl set unnecessary permissions

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);

C# Privilege issues creating folders from Windows service running as Local System account.

I have a service running as Local System.
I'm creating some folders from the service.
These folders are created which don't give people in the "Users" group in windows 7 write access.
How can I create these folders which grant everyone write access?
You can use the logic that I found in this example
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);
}
}
I also found this article that has other examples
http://www.c-sharpcorner.com/uploadfile/babu_2082/adding-groups-user-names-and-permissions-for-a-directory-in-C-Sharp/

Add "Everyone" privilege to folder using C#.NET

I have used the code below to allow Everyone access to a folder:
System.Security.AccessControl.DirectorySecurity sec =
System.IO.Directory.GetAccessControl(directory, AccessControlSections.All);
FileSystemAccessRule accRule = new FileSystemAccessRule("Everyone",
FileSystemRights.Modify,
AccessControlType.Allow);
sec.AddAccessRule(accRule); // setACL
sec.ResetAccessRule(accRule);
Now, the Everyone user is added to the folder, but not with any rights assigned. All the read, write, execute etc. checkboxes are not checked.
First thing I want to tell you is how I found this solution. This is probably more important than the answer because file permissions are hard to get correct.
First thing I did was set the permissions I wanted using the Windows dialogs and checkboxes. I added a rule for "Everyone" and ticked all boxes except "Full Control".
Then I wrote this C# code to tell me exactly what parameters I need to duplicate the Windows settings:
string path = #"C:\Users\you\Desktop\perms"; // path to directory whose settings you have already correctly configured
DirectorySecurity sec = Directory.GetAccessControl(path);
foreach (FileSystemAccessRule acr in sec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount))) {
Console.WriteLine("{0} | {1} | {2} | {3} | {4}", acr.IdentityReference.Value, acr.FileSystemRights, acr.InheritanceFlags, acr.PropagationFlags, acr.AccessControlType);
}
This gave me this line of output:
Everyone | Modify, Synchronize | ContainerInherit, ObjectInherit | None | Allow
So the solution is simple (yet hard to get right if you don't know what to look for!):
DirectorySecurity sec = Directory.GetAccessControl(path);
// Using this instead of the "Everyone" string means we work on non-English systems.
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(path, sec);
This will make the checkboxes on the Windows security dialog match what you have already set for your test directory.
The below code checks for the folder existence, if not created, creates one. And then sets every user- permission of that folder with full permission (read & write).
string file = #"D:\Richi";
private static void GrantAccess(string file)
{
bool exists = System.IO.Directory.Exists(file);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
}
use FileSystemRights.FullControl instead of FileSystemRights.Modify if you want to allow all actions (ACL).

Categories

Resources