Retrieve Security Information of Files using .NET

Posted by: Suprotim Agarwal , on 6/18/2010, in Category .NET Framework
Views: 67594
Abstract: In this article, we will see how to display security information of files kept in a directory.
The System.Security.AccessControl namespace provides programming elements to control access to and audit security-related actions on securable objects. In this article, we will see how to display security information of files kept in a directory.  
Step 1: Our first step is to loop through all the files in the Directory. With .NET 4.0, it becomes easier to enumerate directories and files. Read my blogpost on  7 New methods to Enumerate Directory and Files in .NET 4.0. We will use the DirectoryInfo.EnumerateFiles which returns an enumerable collection of file information in the current directory as shown below:
C#
string dirLocation = @"C:\Program Files\IIS\Microsoft Web Deploy\";
// IEnumerable<FileInfo> new to .NET 4.0
var fileInfo = new DirectoryInfo(dirLocation)
                .EnumerateFiles();
 
foreach (var file in fileInfo)
{
}
 
VB.NET
Dim dirLocation As String = "C:\Program Files\IIS\Microsoft Web Deploy\"
' IEnumerable<FileInfo> new to .NET 4.0
Dim fileInfo = New DirectoryInfo(dirLocation).EnumerateFiles()
 
For Each file In fileInfo
Next file
Step 2: In the next step, we will loop through the IEnumerable<FileInfo> collection obtained using DirectoryInfo.EnumerateFiles() and then use the File.GetAccessControl method to access a FileSecurity object, that encapsulates the access control list (ACL) entries for a specified file. This class represents access rights as a set of rules. The FileSystem.GetAccessRules gets a collection of the access rules associated with the specified security identifier, in our case NTAccount which is a user or group account name on the machine.
C#
foreach (var file in fileInfo)
{
    Console.WriteLine("----Access Control List Entries for {0}---- \n",
                file.Name);           
    FileSecurity fileSec = file.GetAccessControl();
    var authRuleColl =
           fileSec.GetAccessRules(true, true, typeof(NTAccount));
   
...
}
 
VB.NET
For Each file In fileInfo
      Console.WriteLine("----Access Control List Entries for {0}---- " & vbLf, file.Name)
      Dim fileSec As FileSecurity = file.GetAccessControl()
      Dim authRuleColl = fileSec.GetAccessRules(True, True, GetType(NTAccount))
 
Next file
Step 3: The last step is to loop through this collection of access rules (AuthorizationRuleCollection) to access each rule, represented by a FileSystemAccessRule object and print it.
C#
foreach (FileSystemAccessRule fsaRule in authRuleColl)
{
    Console.WriteLine("IdentityReference: {0}",
        fsaRule.IdentityReference);
    Console.WriteLine("AccessControlType: {0}",
        fsaRule.AccessControlType);
    Console.WriteLine("FileSystemRights: {0}",
        fsaRule.FileSystemRights);
    Console.WriteLine();
}
 
VB.NET
For Each fsaRule As FileSystemAccessRule In authRuleColl
      Console.WriteLine("IdentityReference: {0}", fsaRule.IdentityReference)
      Console.WriteLine("AccessControlType: {0}", fsaRule.AccessControlType)
      Console.WriteLine("FileSystemRights: {0}", fsaRule.FileSystemRights)
      Console.WriteLine()
Next fsaRule
The entire source is given here:
C#
using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
 
namespace ConsoleApplication2
{
class Program
{
    static void Main(string[] args)
    {
        string dirLocation = @"C:\Program Files\IIS\Microsoft Web Deploy\";
        // IEnumerable<FileInfo> new to .NET 4.0
        var fileInfo = new DirectoryInfo(dirLocation)
                        .EnumerateFiles();
 
        foreach (var file in fileInfo)
        {
            Console.WriteLine("----Access Control List Entries for {0}---- \n",
                        file.Name);           
            FileSecurity fileSec = file.GetAccessControl();
            var authRuleColl =
                   fileSec.GetAccessRules(true, true, typeof(NTAccount));
            foreach (FileSystemAccessRule fsaRule in authRuleColl)
            {
                Console.WriteLine("IdentityReference: {0}",
                    fsaRule.IdentityReference);
                Console.WriteLine("AccessControlType: {0}",
                    fsaRule.AccessControlType);
                Console.WriteLine("FileSystemRights: {0}",
                    fsaRule.FileSystemRights);
                Console.WriteLine();
            }
            Console.WriteLine("---------------------------");
        }
 
        Console.ReadLine();
    }
}
}
 
VB.NET
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Security.AccessControl
Imports System.Security.Principal
 
Namespace ConsoleApplication2
Friend Class Program
      Shared Sub Main(ByVal args() As String)
            Dim dirLocation As String = "C:\Program Files\IIS\Microsoft Web Deploy\"
            ' IEnumerable<FileInfo> new to .NET 4.0
            Dim fileInfo = New DirectoryInfo(dirLocation).EnumerateFiles()
 
            For Each file In fileInfo
                  Console.WriteLine("----Access Control List Entries for {0}---- " & vbLf, file.Name)
                  Dim fileSec As FileSecurity = file.GetAccessControl()
                  Dim authRuleColl = fileSec.GetAccessRules(True, True, GetType(NTAccount))
                  For Each fsaRule As FileSystemAccessRule In authRuleColl
Console.WriteLine("IdentityReference: {0}", fsaRule.IdentityReference)
Console.WriteLine("AccessControlType: {0}", fsaRule.AccessControlType)
Console.WriteLine("FileSystemRights: {0}",   fsaRule.FileSystemRights)
                        Console.WriteLine()
                  Next fsaRule
                  Console.WriteLine("---------------------------")
            Next file
 
            Console.ReadLine()
      End Sub
End Class
End Namespace
 
OUTPUT
Output
I hope you liked this article and I thank you for viewing it. The entire source code of this article can be downloaded over here
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel