Remove all directory permissions & set new permissions using C# - 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?

Related

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

How to read emails from Clutter outlook folder C#

I am trying to read the emails that are being moved to the clutter folder by outlook. The below code works fine for other folders, but when I try to open the clutter folder the code defaults to the error message indicate the folder does not exist.
oApp = new Microsoft.Office.Interop.Outlook.Application();
oNS = (Microsoft.Office.Interop.Outlook._NameSpace)oApp.GetNamespace("MAPI");
oNS.Logon(null, null, false, false);
oFolder = oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
string folderName = "Clutter";
try
{
oSubfolder = oFolder.Folders[folderName];
for (int i = 1; i <= oSubfolder.Items.Count; i++)
{
item = (Microsoft.Office.Interop.Outlook.PostItem)oFolder.Items[i];
}
}
catch
{
MessageBox.Show("There is no folder named " + folderName +
".", "Find Folder Name");
}
You are assuming Clutter is the child of the Inbox folder. It is Inbox's peer:
oFolder = (Outlook.MAPIFolder)oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent;

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