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
UnauthorizedAccessException
: If you don’t have access to the file, you will get this exception.
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.
CodeProject