如何通过代码给本地Windows用户组IIS_IUSRS设置文件夹读取权限
解决给IIS_IUSRS组授予文件夹权限时的IdentityNotMappedException问题
你遇到的这个IdentityNotMappedException本质原因是多语言版本Windows中内置用户组的显示名称是本地化的——德语版Windows里,IIS_IUSRS这个英文组名并不存在,系统里对应的是德语本地化后的名称,直接用英文名称自然无法映射到正确的身份。
直接使用SecurityIdentifier(SID)是正确的思路,因为SID是跨语言、跨系统的唯一身份标识,不会受本地化影响。你之前用WorldSid能行,就是因为它是内置的标准SID。针对IIS_IUSRS组,我们可以通过WellKnownSidType直接获取它的SID,不需要硬编码组名。
修正后的C#代码
using System.Security.AccessControl; using System.Security.Principal; using System.IO; // 目标文件夹路径 string path = @"你的文件夹路径"; DirectoryInfo directoryInfo = new DirectoryInfo(path); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); // 获取本地机器的SID(作为IIS_IUSRS组的父SID) SecurityIdentifier localMachineSid = new SecurityIdentifier(WellKnownSidType.LocalMachineSid, null); // 获取IIS_IUSRS组的SID SecurityIdentifier iisIusrsSid = new SecurityIdentifier(WellKnownSidType.IIS_IUSRS, localMachineSid); // 添加权限规则 directorySecurity.AddAccessRule( new FileSystemAccessRule( iisIusrsSid, FileSystemRights.Read, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow ) ); // 应用权限设置 directoryInfo.SetAccessControl(directorySecurity);
关键说明
为什么用WellKnownSidType?
WellKnownSidType.IIS_IUSRS是系统预定义的SID类型,不管Windows是德语、英语还是其他语言版本,都能精准定位到对应的IIS应用池组,完全避免本地化名称的问题。必要的运行权限
修改文件夹的访问控制列表(ACL)需要管理员权限,所以你的程序必须以管理员身份运行,否则可能会抛出权限不足的异常。验证SID是否正确
如果你想确认IIS_IUSRS组的SID,可以在德语版Windows中:- 打开本地用户和组(
lusrmgr.msc) - 找到IIS相关的组(德语名称可能是
IIS_IUSRS的德语翻译) - 右键属性 → 安全 → 高级 → 查看SID
- 打开本地用户和组(
内容的提问来源于stack exchange,提问作者nkr
相关产品推荐
相关产品推荐

