Search code examples
c#.net.net-coreaclwindows-server

Set running user as file owner and delete it in .NET Core


I've made a File Cleaner Windows Service (using .NET Core 3 Worker Service hosted in a Windows Service). I set the service to run as Administrator with Full Access.

Now I have two IIS websites running by IIS APP POOL\foo and IIS APP POOL\bar user respectively. Each site has their own C:\web\foo\Uploads\ and C:\web\bar\Uploads\ folders that I want my File Cleaner to periodically delete them.

Even though I set Full Control permission for Uploads folders for Administrator, newly created files by foo and bar are still not deletable by Administrator. I can manually change owner of the files in these folder then delete them (interestingly, in File Explorer, I can just Delete them without any problem), but I don't know how to programmatically do it.

Given that I can give any permission to my running app, how can I set a folder/file owner/full control to the account running it and then delete it?


Solution

  • Thanks to Heretic Monkey comment and the information from various StackOverflow post, I compiled the solution both for setting the file/folder owner and reset its attributes (i.e readonly, system):

    public static class CoreUtils
    {
    
        public static string RunningUser { get; } = $"{Environment.UserDomainName}\\{Environment.UserName}";
        public static NTAccount RunningAccount { get; } = new NTAccount(Environment.UserDomainName, Environment.UserName);
    
    }
    
    void SetOwner(FileInfo file)
    {
        var acl = file.GetAccessControl(System.Security.AccessControl.AccessControlSections.All);
    
        acl.SetOwner(CoreUtils.RunningAccount);
        acl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(
            CoreUtils.RunningUser, System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
    
        file.SetAccessControl(acl);
    }
    

    Also a note is that as in linked article, the API does not support long file name so you need extra processing if your app needs to work with these files.