C# SetAccessControl为Windows服务引发UnauthorizedAccessException

C# SetAccessControl为Windows服务引发UnauthorizedAccessException,c#,windows,C#,Windows,我正在编写一个Windows服务,我需要它做的一件事是在我的程序的安装目录上设置权限,以禁止除管理员以外的任何用户进行写访问(以防止篡改) 现在,我无法进行最基本的更改,给“每个人”对目录的读取和执行权限。我得到的错误是: UnauthorizedAccessException:试图执行未经授权的操作 我的代码是: DirectoryInfo dir = new DirectoryInfo(path); SecurityIdentifier everyone = new SecurityIde

我正在编写一个Windows服务,我需要它做的一件事是在我的程序的安装目录上设置权限,以禁止除管理员以外的任何用户进行写访问(以防止篡改)

现在,我无法进行最基本的更改,给“每个人”对目录的读取和执行权限。我得到的错误是:

UnauthorizedAccessException:试图执行未经授权的操作

我的代码是:

DirectoryInfo dir = new DirectoryInfo(path);

SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
SecurityIdentifier system = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);

DirectorySecurity dSecurity = Directory.GetAccessControl(path);
dSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.ReadAndExecute, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
Directory.SetAccessControl(path, dSecurity);    

我的服务是以“LocalSystem”而不是“LocalService”运行的,所以我不知道为什么我没有访问权限来执行此操作。

有问题的文件夹在哪里?您是否检查了权限以查看
系统
是否具有完全访问权限?