How to give permissions for folders in c#?

private static void GrantAccess(string file)
{
    bool exists = System.IO.Directory.Exists(file);
    if (!exists)
    {
        DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
        Console.WriteLine("The Folder is created Sucessfully");
    }
    else
    {
        Console.WriteLine("The Folder already exists");
    }
    DirectoryInfo dInfo = new DirectoryInfo(file);
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
    dInfo.SetAccessControl(dSecurity);
   
}

The above code will set the access rights of the folder to full control/ read-write to every user (everyone).


I know your pain - filesystem ACLs are a pain to modify and even if it seems to work, it might break in some circumstances. In your case, there's a simple solution, fortunately.

The problem lies with PropagationFlags.InheritOnly. This means that this permission is only applied to items that inherit permissions - e.g. you are granting rights only for the files in this directory and not in any subdirectories.

To grant directory rights that inherit "normally" (i.e. propagate to subdirectories and all files), use the following values for InheritanceFlags and PropagationFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit and PropagationFlags.None.