0

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?

Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • 1
    Does this answer your question? [How to modify file access control in .NET Core](https://stackoverflow.com/questions/40449973/how-to-modify-file-access-control-in-net-core) – Heretic Monkey Apr 17 '20 at 20:32
  • Unfortunately no, I have seen that article before, but don't know how to get the credential of the currently running account (not sure if it's even possible). – Luke Vo Apr 17 '20 at 20:40
  • @HereticMonkey thanks for your lead. From that one and many other articles I have come up with a solution. – Luke Vo Apr 18 '20 at 09:36

1 Answers1

0

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.

Luke Vo
  • 17,859
  • 21
  • 105
  • 181