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

msg*_*ish 1 c# asp.net iis folder-permissions

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

我像这样调用上面的方法......

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

但在本地它的工作。当去服务器不工作。

我尝试使用帐户名称而不是 IUSR,但这也不起作用..


IIS_IUSRS
IIS_WPG
网络服务
大家
等。

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

System.Environment.MachineName + "\\IIS_IUSRS"

IIS_IUSRS_System.Environment.MachineName

System.Environment.UserDomainName + "\\IIS_IUSRS"

etc..
Run Code Online (Sandbox Code Playgroud)

但这也不起作用,但它抛出“无法翻译某些或所有身份引用”

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

请有人帮我解决这个问题..?

小智 5

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