Search code examples
c#windows-servicesfile-security

set file permissions for c:\program files\company\app\file for all users


I've a custom installer program that has worked fine, but it asks the user for admin permission every time it updates an application. I'm creating a windows service that skips this part, but the windows service gives only System and Administrators permissions to the file, and the user cannot execute the new updates.

To correct this I'm trying (after the file downloads/installs to the correct place (from within the windows service, it has the account ServiceAccount.LocalSystem),

FileSecurity access = file.GetAccessControl();
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
access.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.ReadAndExecute, AccessControlType.Allow));

but the setting doesn't take effect. What should I do from here?


Solution

  • I figured it out. I just needed to call,

    file.SetAccessControl(access);
    

    after the above. Apparently file.GetAccessControl passes back a copy of the access control and not the one that controls the file permissions for the file, until you call file.SetAccessControl with the modified permissions.

    There's another caveat I discovered with another file that the service was creating in c:\ProgramData,

    • is that the set has to occur after the file has been written. Applying the set to the file beforehand is ineffective.