Accessing Directory Owner Information in .NET 2

I just came upon this question in a newsgroup and had a quick look at the new classes that .NET 2 offers for access to the Windows file system ACLs and general system security information. In short, to get to the name of a user or group that’s the owner of a directory in the file system, you can use the following code:

DirectoryInfo directoryInfo = new DirectoryInfo(@"c:\Windows");
DirectorySecurity directorySecurity =
  directoryInfo.GetAccessControl(AccessControlSections.Owner);
IdentityReference identityReference =
  directorySecurity.GetOwner(typeof(NTAccount));
// now access identityReference.Value for the readable name

The one thing here that’s a bit hard to find out is the usage of the GetOwner method. Current MS docs tell only that the type you need to pass in is “the primary group for which to get the owner”. I needed to use Reflector to find out that the method that’s actually being called in the end is SecurityIdentifier.Translate, and that the type in question must be one of those that the SecurityIdentifier.IsValidTargetType method likes. The docs for that method, finally, told me that the only two types currently considered valid are the SecurityIdentifier itself and the System.Security.Principal.NTAccount. Good, works fine 😃

Sorry, this blog does not support comments.

I used various blog hosting services since this blog was established in 2005, but unfortunately they turned out to be unreliable in the long term and comment threads were lost in unavoidable transitions. At this time I don't want to enable third-party services for comments since it has become obvious in recent years that these providers invariably monetize information about their visitors and users.

Please use the links in the page footer to get in touch with me. I'm available for conversations on Keybase, Matrix, Mastodon or Twitter, as well as via email.