Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Determining the Owner of a File/Folder in C#.NET and Dealing with General Exceptions

0.00/5 (No votes)
18 Jun 2015 1  
This article will help you determining the owner of a file/folder which is displayed in the Advanced Security Settings.

Determining the Owner of a File/Folder in C#.NET

In order to determine the owner of a file/folder, you would need to use the classes from the following namespaces:

using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

Put the following lines in a function and it will give you the owner name:

FileSecurity fileSecurity = File.GetAccessControl(path);
IdentityReference sid = fileSecurity.GetOwner(typeof(SecurityIdentifier));
NTAccount ntAccount = sid.Translate(typeof(NTAccount)) as NTAccount;
string owner = ntAccount.Value;

Here ‘path’ is the location of the file/folder. 

General Exceptions

  1. UnauthorizedAccessException: If you don’t have access to the file, you will get this exception.
  2. IdentityNotMappedException: "Some or all Identity References could not be transalated."

Whenever any user is created on the machine, a unique security ID is assigned. This SID can be converted to Domain Name\Username format by translating the SID to NTAccount type, but if that user is removed from the machine, then only SID exists. Now if you try to convert the SID to NTAccount type, the above exception would occur. In that case, you may just want to display the SID as follows: 

IdentityReference sid = null;
string owner = null;
try
{

FileSecurity fileSecurity = File.GetAccessControl(path);
sid = fileSecurity.GetOwner(typeof(SecurityIdentifier));
NTAccount ntAccount = sid.Translate(typeof(NTAccount)) as NTAccount;
owner = ntAccount.Value;

}
catch (IdentityNotMappedException ex)
{

If (sid != null)
owner = sid.ToString();

}

Optimizing the Code If You Want to Display the Owner Name of Large Number of Files

If you have too many files, getting the SIDs and translating it to DomainName\Username(s) would be very time consuming. You can optimize the code by finding the SIDs for all the files and once you have all the SIDs, translate them to DomainName\Username.

For example: If you have 10000 files, determine the SID for all the 10000 files. Let's say you get 7 SIDs. Now translate only those 7 SIDs to DomainName\Username format. It will definitely speed up the process.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here