gpt4 book ai didi

c# - 设置目录/子目录/文件的权限

转载 作者:太空宇宙 更新时间:2023-11-03 12:20:58 24 4
gpt4 key购买 nike

我希望能够为特定用户设置目标文件夹中的子文件夹和文件的权限。

到目前为止,我了解了如何为特定文件夹设置权限。但不适用于原始文件夹中的子文件夹和文件。经过广泛的互联网搜索后,我找不到任何关于如何解决这个问题的线索。此外,windows doku 仅显示了如何为一个目录设置权限。

class DirectoryPermissions
{
public static void DirectoryPermissionsMain(string Directory, string Account, string Rights, int Takeaway, string Domain)
{
try
{
string DirectoryName = Directory;

Console.WriteLine("Adding access control entry for " + DirectoryName);
if(Takeaway == 0 && Rights.Equals("Read")){
AddDirectorySecurity(DirectoryName, Domain + @"\" + Account, FileSystemRights.ReadData, AccessControlType.Allow);

Console.WriteLine("Removing access control entry from " + DirectoryName);
}

MessageBox.Show("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);

}
}

我希望你们中的一个能给我指出正确的方向。

最佳答案

您必须添加另一个 AccessRule,并将 InheritanceFlags 设置为 ContainerInherit AND ObjectInherit。

要获得传播到子文件夹的权限,PropagationFlag 设置为仅继承。

下面是一个例子

    public void PropogateSecurity(string userid,string directory)
{

var myDirectoryInfo = new DirectoryInfo(directory);
var myDirectorySecurity = myDirectoryInfo.GetAccessControl();
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(userid, FileSystemRights.Modify, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);

}

您也可以使用递归来完成此操作,但以上是我的首选方法,因为清理权限会很烦人。

关于c# - 设置目录/子目录/文件的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268175/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com