Changing file owner results in UnauthorizedAccessException

54 Views Asked by At

I have a small WinForms tool which occasionally creates ZIP archives of files before performing critical modifications. The tool also has backup trimming implemented, and here I've stumbled upon a problem. If an older backup was created by an Admin user, it cannot be trimmed by a low-privileged user.

I tried to change the owner of a newly created ZIP file, from current user to BUILTIN\Users (it's okay for my purposes):

private static void ChangeBackupOwner(string FilePath)
{
    try
    {
        FileInfo fi = new(FilePath);
        FileSecurity fs = fi.GetAccessControl(AccessControlSections.Owner);
        var sid = System.Security.Principal.WellKnownSidType.WinBuiltinIUsersSid;
        System.Security.Principal.SecurityIdentifier identity = new(sid, null);
        fs.SetOwner(identity);
        fi.SetAccessControl(fs);
    }
    catch (Exception ex)
    {
        Logger.PostMessage(ex.ToString());
    }
}

On Windows 10, the code seems to be doing what it's supposed to do, but the last line in the try block throws System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.

After researching the issue, I've found several similar SO questions, but all of them are related to changes of access permissions, not the owner, and most of them are old and refer to the .NET Framework.

Can it be done in .NET, and if so, how?

P.S. I would definitely prefer to avoid any kind of process elevation, as it would be a complete overkill for the job. If it can't be done without triggering UAC, so be it - I'll just skip undeletable files under limited users, so that next time an admin takes a backup, they will be able to trim their own stuff. Still, I'm curious how it can be done.

1

There are 1 best solutions below

0
Roger Wolf On

Although I still don't have the answer to the question as it stands, I seem to have found the solution of the original problem.

After much looking into files' and folders' permissions, I've noticed that the parent folder, where the app puts the backups, doesn't have FullControl permission for the BUILTIN\Users group. As soon as I set it, limited user became capable of deleting any file.

Having said that, I'm still looking forward to learning the answer to this question.