Inside and Out…

An attempt to understand technology better…

Working with NTFS Access Control using .NET Framework 2.0

Posted by Gaurav Khanna on July 12, 2005

.NET Framework 2.0 (“Whidbey”) has introduced a new set of classes in the Framework Class Library (FCL) that allows you to work with the NTFS Access Control Lists. You can get object owners, security descriptors, create security descriptors, and much more. All of this resides under the System.Security.AccessControl namespace.

Below is a snippet that exemplifies how to use it. Scenario: You need to create a child folder without the permissions inherited by the parent folder, but with only permissions explicitly set on the parent folder.

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Security.AccessControl; 
using System.IO; 
using System.Security.Principal;

namespace AceInheritRemove
{

    class Program
    {

        static void Main(string[] args)
        {
            // Get the object and its SecDescp

            DirectoryInfodir = newDirectoryInfo("e:\\kgk\\test"); 
            DirectorySecuritysec = dir.GetAccessControl(AccessControlSections.All); 

            // Create an empty Security Descp... 
            DirectorySecuritysecNew = newDirectorySecurity();

            // Get the explicit perms on the object. 
            AuthorizationRuleCollectioncol= sec.GetAccessRules(true, false, typeof(SecurityIdentifier));

            // List all the explicitly set permissions on the object... 
            foreach(FileSystemAccessRulerule in col)
            {

                // Add the explicit permission to the new Security Descp. 
                secNew.AddAccessRule(rule); 
                Console.WriteLine("{0}", rule.FileSystemRights.ToString());
            }

            // Create a child folder with the explicit permissions only... 
            DirectoryInfoinfo2 = newDirectoryInfo("e:\\kgk\\Test\\Child"); 
            info2.Create(secNew);

        }

    }
}

Advertisements

One Response to “Working with NTFS Access Control using .NET Framework 2.0”

  1. […] by Gaurav Khanna on July 12th, 2005 Continuing from my last post, the same can be achieved using SetAccessRuleProtection as shown […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: