System.UnauthorizedAccessException when giving access to new folder - c#

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

Related

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?

How can i remove the permission on denied folder?

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

c# - sharing a folder on local network

I try to share a folder on local network for a special group.
I create the group, then I add the current user to this group. After this I share the folder on the local network with all the permisson to access to this for the group. In network I see the folder, all the permissons is granted for the group, it seems everything fine, but I can't access the folder on the local network.
I use this code:
string ShareName = "SpecialShare";
string Description = "This is a test";
string folderPath = #"c:\ApplicationFolder\AppData";
try
{
NTAccount ntAccount = new NTAccount("SpecialGroup");
SecurityIdentifier oGroupSID = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
byte[] utenteSIDArray = new byte[oGroupSID.BinaryLength];
oGroupSID.GetBinaryForm(utenteSIDArray, 0);
ManagementClass oGroupTrustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null);
oGroupTrustee["Name"] = "SpecialGroup";
oGroupTrustee["SID"] = utenteSIDArray;
ManagementClass oGroupACE = new ManagementClass(new ManagementPath("Win32_ACE"), null);
oGroupACE["AccessMask"] = 2032127; //full access
oGroupACE["AceFlags"] = AceFlags.ObjectInherit | AceFlags.ContainerInherit;
oGroupACE["AceType"] = AceType.AccessAllowed;
oGroupACE["Trustee"] = oGroupTrustee;
ManagementObject oGroupSecurityDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null);
oGroupSecurityDescriptor["ControlFlags"] = 4;
oGroupSecurityDescriptor["DACL"] = new object[] { oGroupACE };
DirectoryInfo dInfo = new DirectoryInfo(folderPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule("SpecialGroup", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);
ManagementClass managementClass = new ManagementClass("Win32_Share");
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
//MessageBox.Show(managementClass.Derivation[0]);
inParams["Description"] = Description;
inParams["Name"] = ShareName;
inParams["Path"] = folderPath;
inParams["Type"] = 0; //Disk Drive
inParams["MaximumAllowed"] = null;
inParams["Password"] = null;
inParams["Access"] = oGroupSecurityDescriptor;
ManagementBaseObject outParams;
outParams = managementClass.InvokeMethod("Create", inParams, null);
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
throw new Exception();
ManagementObject share = new ManagementObject(managementClass.Path + ".Name='" + ShareName + "'");
share.InvokeMethod("SetShareInfo", new object[] { Int32.MaxValue, Description, oGroupSecurityDescriptor });
dInfo.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

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