C#代码自动授予对Windows Server 2008上的文件夹的IIS写入权限? 目前抛出exception

我正在尝试编写一个命令行工具,它将使Windows Server 2008上的IIS7.5对wwwroot中的文件夹具有写入权限,以便Web应用程序可以访问其基本目录中的特定文件夹。 以前,您可以通过在给予该组修改访问权限的文件夹上分配IIS_WPG组来执行此操作。

在Server 2008中,我正在尝试使用IIS_IUSRS执行相同的操作,但是出现exception。

这是代码:

private static void ManagePermissions(string directory, string account, FileSystemRights rights, AccessControlType controlType, bool addAccess) { DirectoryInfo directoryInfo = new DirectoryInfo(directory); DirectorySecurity directorySecurity = directoryInfo.GetAccessControl(); if (addAccess) directorySecurity.AddAccessRule( new FileSystemAccessRule(account, rights, controlType)); else directorySecurity.RemoveAccessRule( new FileSystemAccessRule(account, rights, controlType)); directoryInfo.SetAccessControl(directorySecurity); } 

对此方法的调用如下:

 ManagePermissions( "c:\inetpub\wwwroot", "MACHINENAME\IIS_IUSRS", FileSystemRights.Modify, AccessControlType.Allow, true); 

当执行对ManagePermissions的调用时,将引发具有以下类型和消息的exception:

 System.Security.Principal.IdentityNotMappedException: Some or all identity references could not be translated. 

我已多次检查以确保MACHINENAME \ IIS_IUSRS与此代码正在执行的计算机上的本地用户管理器中的用户完全匹配。 本机不参与Windows域。

如果您需要进一步澄清,请与我们联系。

IIS_IUSRS是内置组,因此不应使用[machinename]\IIS_IUSRS引用它,而应使用BUILTIN\IIS_IUSRS引用它。 像这样:

 ManagePermissions( "c:\inetpub\wwwroot", "BUILTIN\IIS_IUSRS", FileSystemRights.Modify, AccessControlType.Allow, true); 

切换到引用用户的方式修复了我的代码。 我获得的帐户方式与示例中引用的方式略有不同:

 IdentityReference user = new NTAccount(UserDomain + @"\" + UserName); 

然后通过不同的构造函数使用它,这也可能影响翻译,但我对此表示怀疑:

 var rule = new FileSystemAccessRule(user, ..., ..., ..., ...); 

更新:最近我发现在非英语窗口(Windows server 2008 R2 x64 IIS7)上向用户IIS_IUSRS添加完全控制时出错。

尽管IIS_IUSRS没有翻译,但它前面的“BUILTIN”可能会导致错误

因此,请注意使用“BUILTIN \ IIS_IUSRS”,而只使用“IIS_IUSRS” – 它适用于英语和非英语窗口