using System.Security.AccessControl; using System.Security.Principal; namespace Agent.Windows.Security; public static class UserOnlyDirectory { public static void Ensure(string path) { Directory.CreateDirectory(path); using WindowsIdentity identity = WindowsIdentity.GetCurrent(); SecurityIdentifier user = identity.User ?? throw new InvalidOperationException("Current Windows identity has no user SID."); var security = new DirectorySecurity(); security.SetOwner(user); security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); security.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); FileSystemAclExtensions.SetAccessControl(new DirectoryInfo(path), security); } }