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

Mar*_*p51 5 c# ntfs windows-server-2008 iis-7.5

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

在Server 2008中,我正在尝试使用IIS_IUSRS执行相同的操作,但是例外情况正在发生.

这是代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

对此方法的调用如下:

ManagePermissions(
                  "c:\inetpub\wwwroot", 
                  "MACHINENAME\IIS_IUSRS", 
                  FileSystemRights.Modify, 
                  AccessControlType.Allow, 
                  true);
Run Code Online (Sandbox Code Playgroud)

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

System.Security.Principal.IdentityNotMappedException: 
    Some or all identity references could not be translated.
Run Code Online (Sandbox Code Playgroud)

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

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

Jam*_*Eby 5

IIS_IUSRS是一个内置的组,因此它不应该被引用[machinename]\IIS_IUSRS,但用BUILTIN\IIS_IUSRS.像这样:

ManagePermissions( 
                  "c:\inetpub\wwwroot",  
                  "BUILTIN\IIS_IUSRS",  
                  FileSystemRights.Modify,  
                  AccessControlType.Allow,  
                  true);
Run Code Online (Sandbox Code Playgroud)

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

IdentityReference user = new NTAccount(UserDomain + @"\" + UserName);
Run Code Online (Sandbox Code Playgroud)

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

var rule = new FileSystemAccessRule(user, ..., ..., ..., ...);
Run Code Online (Sandbox Code Playgroud)