[英]Directory.SetAccessControl set unnecessary permissions
我正在嘗試將程序的安裝文件夾權限設置為僅限於管理員。
有兩種情況:文件夾需要創建和文件夾已經存在。
這是我的代碼:
public static void CreatePrivateFolder(string path)
{
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
DirectorySecurity securityRules = new DirectorySecurity();
FileSystemAccessRule fsRule =
new FileSystemAccessRule(sid, FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None, AccessControlType.Allow);
securityRules.SetAccessRule(fsRule);
if (Directory.Exists(path))
{
Directory.SetAccessControl(path, securityRules);
}
else
{
Directory.CreateDirectory(path, securityRules);
}
}
當文件夾需要創建時, CreateDirectory
工作正常,文件夾的權限僅限於管理員。
奇怪的是,當我重新運行此代碼並流向SetAccessControl
- 文件夾的權限被重置為沒有訪問限制的常規文件夾。
我做錯了什么?
文件夾安全結果(對於路徑c:\\\\folderCheck
):
更新anrei解決方案來回答我的問題。 但是,它似乎以不同的方式存在相同的問題:如果該文件夾已經存在且具有不受限制的權限,則 anrei 的代碼似乎不起作用。 文件夾的權限保持不受限制。
謝謝!
使用它代替if (Directory.Exists(path))
塊。
// what is
var existingACL = Directory.GetAccessControl(path);
// remove everything from what is
foreach (FileSystemAccessRule rule in existingACL.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
existingACL.RemoveAccessRuleAll(rule);
// add yours to what is
existingACL.AddAccessRule (fsRule);
// set again
Directory.SetAccessControl(path, existingACL);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.