How to set folder permission

2019-04-15 03:14发布

问题:

How can I create/edit/add folder permission to specific folder? There is a folder called "test" in local disk C. How do I set permission to that folder using C#?

I wrote some code already:

public void getusers()
{
    SelectQuery squery = new SelectQuery("Win32_UserAccount", "Domain='" + System.Environment.UserDomainName.ToString() + "'");
    try
    {
        ManagementObjectSearcher msearchar = new ManagementObjectSearcher(squery);

        foreach (ManagementObject mobject in msearchar.Get())
        {
            comboBox1.Items.Add(mobject["Name"]);
        }
    }
    catch (Exception e) { MessageBox.Show(e.ToString()); }
}

private void button1_Click(object sender, EventArgs e)
{
    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.ShowDialog();
    textBox1.Text = fbd.SelectedPath.ToString();
}

private void button2_Click(object sender, EventArgs e)
{
    DirectoryInfo myDirectoryInfo = new DirectoryInfo(textBox1.Text);

    DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
    string User = System.Environment.UserDomainName + "\\" + comboBox1.SelectedItem.ToString();

    myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
    //myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, FileSystemRights.Write, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));

    myDirectoryInfo.SetAccessControl(myDirectorySecurity);
    MessageBox.Show("Permissions Altered Successfully" + User);
}

This code already successfully adds the User to the folder but the permissionIi set to that folder is not inherited at all. Did I miss something? Or could someone guide me how to inherit the permission to that folder?

回答1:

If by inherited you mean that all child objects receive the same permissions, you will need to set your PropagationFlags to InheritOnly. Further if you want your files to also match the permission of the ruleset, change your InheritanceFlags to ObjectInherit. try using this line below.

myDirectoryInfo.AddAccessRule(new FileSystemAccessRule(User, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow)); 


回答2:

It looks to me like you are just missing this flag, which you would join using the bitwise operator in your parameter list:

InheritanceFlags.ObjectInherit

There are more details, including a link to a Google Spreadsheet with a matrix of permissions and settings, in this thread: Setting Inheritance and Propagation flags with set-acl and powershell

Hope this helps...