如何授予我的应用程序为所有用户创建的文件的完全权限?


74

我开发的工具需要向其创建的文件授予访问权限“完全控制”。需要从所有Windows帐户甚至将来的帐户中读取,修改和删除它。可以实现吗?

我知道我可以为SPECIFIC_USER尝试以下操作:

FileSystemAccessRule rule = new FileSystemAccessRule(SPECIFIC_USER, FileSystemRights.FullControl, AccessControlType.Allow);
FileSecurity fSecurity = File.GetAccessControl(filePath);
fSecurity.SetAccessRule(rule);
File.SetAccessControl(filePath, fSecurity);

但是,如何授予所有用户呢?甚至将来的帐户?如果后一部分不可行,该如何执行第一个要求?

谢谢。

编辑:

这是为我工作的代码。摘自回答者的链接。

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

请注意PropagationFlags.NoPropagateInherit这是必需的(在链接的最后提到)。它确实为以后的帐户授予特权。


18
注意,不要使用“所有人”,而应使用new SecurityIdentifier(WellKnownSidType.WorldSid, null)它返回SecurityIdentifier对象。每个人都只能在英语Windows装置上工作,使用其他方法可确保它与多种语言版本兼容。
— Angelo Vargas

@trukin可以回答吗?谢谢
— nawfal 2013年

@nawfal:我遇到了同样的问题,一旦安装了应用程序,我需要授予安装文件夹的访问权限,但是我可以在哪里编写此代码?
— Hina Khuman

@HinaKhuman授予安装文件夹特权可以由安装程序更好地处理。我不知道您正在使用哪一个,但是应该很简单。如果您想从C#中执行此操作,则可以从任意位置调用GrantAccess方法,但您的应用程序本身应该具有权限。
— nawfal

@nawfal:谢谢!看到详细的问题在这里:stackoverflow.com/q/48165315/5743676
— Hina Khuman

Answers:


126

注意使用此工具的人。

当使用文字字符串作为时FileSystemAccessRule,应使用WellKnownSidType.WorldSid而不是"everyone"。

原因是因为有多种窗口语言,并且每个人仅适用于EN语言,因此对于西班牙语,可能是“ Todos”(或其他名称)。

using System.Security.AccessControl;
using System.Security.Principal;
using System.IO;

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

非常感谢..一直在努力解压缩文件并设置对.mdf文件的权限(因为我得到了只读错误)。谢谢!
— CularBytes

请问返回值的目的?
— hypehuman15年

@hypehuman哦,真的没有,它是从某个地方调用的,如果失败了(例如GrantAccess捕获了一个异常,那么它将返回false),那么任何使用的代码都不应继续,因为没有授予任何权限。
— 安吉洛·巴尔加斯

找不到DirectorySecurity。什么是参考库?我添加了3行“正在使用...”,仍然出错。
— anhtv13

13

您将需要完全控制计算机上的“所有人”组。在MSDN上找到了有关此帖子。

希望这对您有用。


谢谢,虐待。这样是否可以授予将来的帐户访问权限?
— nawfal 2012年

感谢它的工作,并授予访问未来用户帐户的权限。请接受我的编辑,以便其他人知道应该做什么。
— nawfal 2012年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.