How can i remove the permission on denied folder? - c#

private bool GrantAccess(string fullPath)
{
DirectoryInfo dInfo = new DirectoryInfo(fullPath);
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);
return true;
}
Am using this method for remove the denied permission but its not working, please if any help to fix this.

using System;
using System.IO;
using System.Security.AccessControl;
namespace FileSystemExample
{
class DirectoryExample
{
public static void Main()
{
try
{
string DirectoryName = "TestDirectory";
Console.WriteLine("Adding access control entry for " + DirectoryName);
// Add the access control entry to the directory.
AddDirectorySecurity(DirectoryName, #"MYDOMAIN\MyAccount", FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Removing access control entry from " + DirectoryName);
// Remove the access control entry from the directory.
RemoveDirectorySecurity(DirectoryName, #"MYDOMAIN\MyAccount", FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Done.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.ReadLine();
}
// 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);
}
// Removes an ACL entry on the specified directory for the specified account.
public static void RemoveDirectorySecurity(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.RemoveAccessRule(new FileSystemAccessRule(Account,
Rights,
ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity);
}
}
}
more information here:
https://msdn.microsoft.com/en-us/library/system.io.directory.setaccesscontrol(v=vs.110).aspx
make sure your application run in high privilege

Related

System.UnauthorizedAccessException when giving access to new folder

I am using below code to grant access to IIS Folder:
string path=#"C:\inetpub\logs\LogFiles\W3SVC6\";
AddDirectorySecurity(path, "everyone", FileSystemRights.ReadData, AccessControlType.Allow);
public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
DirectoryInfo dInfo = new DirectoryInfo(FileName);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(Account, Rights,
ControlType));
dInfo.SetAccessControl(dSecurity);
}

Copy parent folder permissions to child files

So, basically I have an issue where these files are being moved into folders from a couple layers up and the permissions of the child are not being inheritied for some reason. From what I can tell this is the intended function of windows but I need it to work different so I decided to do this:
foreach (string directory in System.IO.Directory.GetDirectories(#"path", "*", SearchOption.TopDirectoryOnly))
{
foreach (string file in System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly))
{
DirectorySecurity DS = System.IO.Directory.GetAccessControl(directory);
FileSecurity FS = new FileSecurity();
System.IO.FileInfo FI = new FileInfo(file);
foreach (FileSystemAccessRule rule in DS.GetAccessRules(true, true, typeof(NTAccount)))
{
FS.AddAccessRule(rule);
}
FI.SetAccessControl(FS);
}
}
However this is generating an error while doing "fs.addaccessrule" saying:
system.argumentexception no flags can be set
I can't figure out how i'm supposed to move the permissions from the parent folder to the child file.
This is the solution I came up with, just creating a new rule based on the rule I want to use and removing the inheritedflags.
foreach (string directory in System.IO.Directory.GetDirectories(#"path", "*", SearchOption.AllDirectories))
{
foreach (string file in System.IO.Directory.GetFiles(directory, "*", SearchOption.TopDirectoryOnly))
{
DirectorySecurity DS = System.IO.Directory.GetAccessControl(directory, AccessControlSections.Access);
FileSecurity FS = new FileSecurity();
System.IO.FileInfo FI = new FileInfo(file);
foreach (FileSystemAccessRule rule in DS.GetAccessRules(true, false, typeof(NTAccount)))
{
FileSystemAccessRule nRule = new FileSystemAccessRule(rule.IdentityReference, rule.FileSystemRights, InheritanceFlags.None, rule.PropagationFlags, rule.AccessControlType);
FS.AddAccessRule(nRule);
}
FI.SetAccessControl(FS);
}
}

Creation of File with write access in c#

I need to create a file in the path c:/Progran File (x86). But it throws a error saying access denied. I have tried the below code, but it didn't help.
private bool GrantAccess(string fullPath)
{
DirectoryInfo dInfo = new DirectoryInfo(fullPath);
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);
return true;
}

Remove all directory permissions & set new permissions using C#

I want to remove previously set directory permissions to a folder & set new permissions as per requirement.
I have referred this link
Remove All Directory Permissions
but once i removed all permission it never allows me to set new rules.
my code
DirectoryInfo myDirectoryInfo = new DirectoryInfo("D:\\Shared\\Testing");
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
string User = System.Environment.UserDomainName + "\\" + Convert.ToString(dt_UserDetails.Rows[i]["AD_NAME"]);
AuthorizationRuleCollection rules = myDirectorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
myDirectorySecurity.SetAccessRuleProtection(true, false);
if (Convert.ToInt16(dt_UserDetails.Rows[i]["ACCESS_CONTROL_TYPE"]) == 1)
{
new FileSystemAccessRule(User, FileSystemRights.ChangePermissions, AccessControlType.Allow);
}
else if (Convert.ToInt16(dt_UserDetails.Rows[i]["ACCESS_CONTROL_TYPE"]) == 0)
{
new FileSystemAccessRule(User, FileSystemRights.ChangePermissions, AccessControlType.Deny);
}
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
Is there any solution for this?

Create and set permissions on new home folder programmatically

I have created an app to standardize user creation for our AD domain. Now I would like to be able to create, share and set permissions on the folder. I know how to create a remote folder, but I am unclear on the best way to go about sharing and setting permissions in VB08.
Thanks in advance,
Christopher
Just so people know what I ended up going with, here is the final successful code to create a remote folder, set NTFS permissions on the folder to full control for the selected user and then create a share on the new folder with full permissions for everyone.
using System.IO;
using System.Management;
using System.Security.AccessControl;
public static void CreateFolder(String accountName, String homeFolder)
{
String folderName;
String localfolderpath;
String shareName;
try
{
folderName = "\\\\server\\c$\\Home\\" + homeFolder + "\\" + accountName;
Directory.CreateDirectory(folderName);
localfolderpath = "C:\\Home\\" + homeFolder + "\\" + accountName;
shareName = accountName + "$";
FolderACL(accountName, folderName);
makeShare(localfolderpath, shareName);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.ToString());
}
}
public static void FolderACL(String accountName, String folderPath)
{
FileSystemRights Rights;
//What rights are we setting?
Rights = FileSystemRights.FullControl;
bool modified;
InheritanceFlags none = new InheritanceFlags();
none = InheritanceFlags.None;
//set on dir itself
FileSystemAccessRule accessRule = new FileSystemAccessRule(accountName, Rights, none, PropagationFlags.NoPropagateInherit, AccessControlType.Allow);
DirectoryInfo dInfo = new DirectoryInfo(folderPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified);
//Always allow objects to inherit on a directory
InheritanceFlags iFlags = new InheritanceFlags();
iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
//Add Access rule for the inheritance
FileSystemAccessRule accessRule2 = new FileSystemAccessRule(accountName, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow);
dSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified);
dInfo.SetAccessControl(dSecurity);
}
private static void makeShare(string filepath, string sharename)
{
try
{
String servername = "server";
// assemble the string so the scope represents the remote server
string scope = string.Format("\\\\{0}\\root\\cimv2", servername);
// connect to WMI on the remote server
ManagementScope ms = new ManagementScope(scope);
// create a new instance of the Win32_Share WMI object
ManagementClass cls = new ManagementClass("Win32_Share");
// set the scope of the new instance to that created above
cls.Scope = ms;
// assemble the arguments to be passed to the Create method
object[] methodargs = { filepath, sharename, "0" };
// invoke the Create method to create the share
object result = cls.InvokeMethod("Create", methodargs);
MessageBox.Show(result.ToString());
}
catch (SystemException e)
{
Console.WriteLine("Error attempting to create share {0}:", sharename);
Console.WriteLine(e.Message);
}
}
here is nice tutorial http://weblogs.asp.net/cumpsd/archive/2004/02/08/69403.aspx
and home path you can get from %HOMEPATH% env. variable

Categories