Retrieve Security Information of Files using .NET

Posted by: Suprotim Agarwal , on 6/18/2010, in Category .NET Framework
Views: 90544
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

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

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 The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!