如何在C#中为IIS用户授予文件夹权限?

我需要为IIS用户提供文件夹权限。
其实我写了这样的代码..

public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights,AccessControlType ControlType) { DirectoryInfo dInfo = new DirectoryInfo(FileName); DirectorySecurity dSecurity = dInfo.GetAccessControl(); dSecurity.AddAccessRule( new System.Security.AccessControl.FileSystemAccessRule(objUser, Rights, ControlType)); dInfo.SetAccessControl(dSecurity); } 

我这样称呼上面这个方法……

 void givepermission() { DirectoryInfo a = new DirectoryInfo(Server.MapPath("~/resources")); AddDirectorySecurity(Server.MapPath("~/"), "IUSR", FileSystemRights.FullControl,AccessControlType.Allow); } 

但是本地工作。 什么时候服务器不工作。

而不是IUSR我试过跟随帐户名称,但也没有工作..

IIS_IUSRS
IIS_WPG
网络服务
大家
等等..

而是IIS_IUSRS。 我也这样试过……

 System.Environment.MachineName + "\\IIS_IUSRS" IIS_IUSRS_System.Environment.MachineName System.Environment.UserDomainName + "\\IIS_IUSRS" etc.. 

但这也行不通,但它正在抛出“部分或全部身份引用无法翻译”

注意:我不想手动设置权限

请有人帮我这个..?

基于Application Pool Identities文章:

IIS在Windows Server 2008和Windows Vista的Service Pack 2(SP2)中引入了新的安全function。 它被称为应用程序池标识。 应用程序池标识允许您在唯一帐户下运行应用程序池,而无需创建和管理域或本地帐户。 应用程序池帐户的名称对应于应用程序池的名称。

这里有一个很好的解释:

在Windows 7中,IIS应用程序池隔离已经达到了不同的级别。 IIS7(Windows Server 2008)中引入的新更改是将应用程序池作为AppPoolIdentiy运行的新选项。 但是,IIS7中的应用程序池标识的默认值保持不变 – NetworkService。 在IIS7.5中,AppPoolIdentiy成为默认值。 因此,以前希望将其应用程序池标识的权限设置为“NT Service \ NetworkService”的脚本现在必须为“IIS AppPool”设置权限(ACL) – 为每个新应用程序池创建的用户帐户。

因此,要设置DefaultAppPool的权限, 脚本将需要为“IIS AppPool \ DefaultAppPool”设置ACL

 public static void FolderPermission(String accountName, String folderPath) { try { FileSystemRights Rights; //What rights are we setting? Here accountName is == "IIS_IUSRS" Rights = FileSystemRights.FullControl; bool modified; var none = new InheritanceFlags(); none = InheritanceFlags.None; //set on dir itself var accessRule = new FileSystemAccessRule(accountName, Rights, none, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); var dInfo = new DirectoryInfo(folderPath); var dSecurity = dInfo.GetAccessControl(); dSecurity.ModifyAccessRule(AccessControlModification.Set, accessRule, out modified); //Always allow objects to inherit on a directory var iFlags = new InheritanceFlags(); iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit; //Add Access rule for the inheritance var accessRule2 = new FileSystemAccessRule(accountName, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow); dSecurity.ModifyAccessRule(AccessControlModification.Add, accessRule2, out modified); dInfo.SetAccessControl(dSecurity); } catch (Exception ex) { MessageBox.Show("Error"); } }