Freigeben über


Who has access to a folder? (C#)

Hi all, welcome back,

The following .NET 2.0 sample shows how to get security info from a folder to find out the permissions for users/groups on it:

 using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Variables
            //
            string strFolderPath = "";
            DirectoryInfo dirInfo = null;
            DirectorySecurity dirSec = null;
            int i = 0;

            try
            {
                // Read the path to the directory
                //
                do
                {
                    Console.Write("Enter existing directory > ");
                    strFolderPath = Console.ReadLine();
                } while (!Directory.Exists(strFolderPath));

                // Get the ACL of the directory
                //
                dirInfo = new DirectoryInfo(strFolderPath);
                dirSec = dirInfo.GetAccessControl();

                // Show the ACEs of the ACL
                //
                i = 0;
                foreach (FileSystemAccessRule rule in dirSec.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    Console.WriteLine("[{0}] - Rule {1} {2} access to {3}",
                    i++,
                    rule.AccessControlType == AccessControlType.Allow ? "grants" : "denies",
                    rule.FileSystemRights,
                    rule.IdentityReference.ToString());
                }
            }
            catch (Exception ex)
            {
                Console.Write("EXCEPTION: ");
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("\n<
>");
            Console.Read();
        }
    }
}

 

I hope this helps.

Cheers,

 

Alex (Alejandro Campos Magencio)

Comments

  • Anonymous
    November 06, 2008
    It was of great help!Thanks ;-)
  • Anonymous
    January 11, 2009
    Thanks a lot. But how do I interpret the FileSystemRights? Sometimes it is text ("Full Control") and other times it is just a decimal number.
  • Anonymous
    February 08, 2011
    Thank You!