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 đŸ™‚

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s