Tuesday, 16 June 2015

Determining the owner of a file\folder in C#.Net and handling with general exceptions

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 translated”


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.

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

No comments:

Post a Comment