C# – How to give Folder Permission for IIS User in C#

asp.netc++folder-permissionsiis

I need to give Folder Permission for IIS User.
Actually I wrote code like this..

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);
}

I calling this above method like this…

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

But Locally its working. When going server not working.

Instead of IUSR I tried following Account Names but that also not working ..

IIS_IUSRS
IIS_WPG
Network Service
Everyone
etc..

Instead IIS_IUSRS. I Tried like this also…

System.Environment.MachineName + "\\IIS_IUSRS"

IIS_IUSRS_System.Environment.MachineName

System.Environment.UserDomainName + "\\IIS_IUSRS"

etc..

but this also not working, but it's throwing
"Some or all identity references could not be translated"

Note:I Don't want to set the Permission Manually

Please can some one help me with this..?

Best Solution

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");
        }
    }