Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all default file permissions

I have an C# network application that prompts admins for network proxy authentication information. I ask the user if they want to save this information, which if they choose yes, I encrypt in a unique local file for the user. I would then like to remove all file permissions except the user that created it, but all other users to have the ability to delete the file.

Now, I found MS article below, but it's not helping if I don't know the default users that were setup on the file in the first place. Is there a remove all file permissions? I can then add the individual rights I'm wanting to setup for full access by current user and delete permissions for "All Users" or "Authenticated Users", which looks to be different depending on version of Windows. http://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol.aspx

like image 666
Chizl Avatar asked Jan 13 '23 10:01

Chizl


1 Answers

I figured it out..

    public void SetFileSecurity(String filePath, String domainName, String userName)
    {
        //get file info
        FileInfo fi = new FileInfo(filePath);

        //get security access
        FileSecurity fs = fi.GetAccessControl();

        //remove any inherited access
        fs.SetAccessRuleProtection(true, false);

        //get any special user access
        AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));

        //remove any special access
        foreach (FileSystemAccessRule rule in rules)
            fs.RemoveAccessRule(rule);

        //add current user with full control.
        fs.AddAccessRule(new FileSystemAccessRule(domainName + "\\" + userName, FileSystemRights.FullControl, AccessControlType.Allow));

        //add all other users delete only permissions.
        fs.AddAccessRule(new FileSystemAccessRule("Authenticated Users", FileSystemRights.Delete, AccessControlType.Allow));

        //flush security access.
        File.SetAccessControl(filePath, fs);
    }
like image 63
Chizl Avatar answered Jan 17 '23 18:01

Chizl