DotNetCurry Logo

Retrieve Security Information of Files using .NET

Posted by: Suprotim Agarwal , on 6/18/2010, in Category .NET Framework
Views: 75386
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
  • Please Share this article if you think it was worth reading. Thanks!
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
comments powered by Disqus