1

I'd like to be able to use something like Directory.CreateDirectory() and File.WriteAllText() to create/write a file in such a way that even if the file is created/written initially by an administrator, it will still be editable/overwritable by a standard non-admin user after that. Currently if I use an admin account to perform the directory creation and file creation, then after that I am not able to use a regular/standard user account to modify/delete the file. Is it possible to strip the admin privileges at the time of creation by the creator, if the first create/write is performed by an admin user? Any type of user might perform the first create/write, but after that any other user still needs to be able to overwrite/delete the same file. Is this possible?

blitz_jones
  • 1,048
  • 2
  • 10
  • 22

2 Answers2

0

@HansPassant provided a link that contained the answer:

Why can .NET app not overwrite file when user is Administrator?

Right after creating the directory and file, this code can be run to update the ACL for the file:

var fileSecurity = File.GetAccessControl(path);

fileSecurity.AddAccessRule(
    new FileSystemAccessRule(
        new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
        FileSystemRights.FullControl,
        AccessControlType.Allow));

File.SetAccessControl(path, fileSecurity);
blitz_jones
  • 1,048
  • 2
  • 10
  • 22
-1

Check out https://github.com/mattjohnsonpint/SimpleImpersonation

This library allows you to run code as another Windows user, as long as you have their credentials. It achives this using the LogonUser Windows API, and thus can only provide the functionality provided by that API.