Use .NET To Grant NTFS Access Rights

By Robbe Morris

Here is a code sample showing how to grant NTFS read and modify access rights to folders.

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

public class NTFS
{
#region Grant Modify Access To Folder
public static bool GrantModifyAccessToFolder(string windowsAccountUserName, string folderName)
{

if (String.IsNullOrEmpty(windowsAccountUserName))  return false;
if (String.IsNullOrEmpty(folderName)) return false;
if (!Directory.Exists(folderName))  return false;

var directory = new DirectoryInfo(folderName);

var directorySecurity = directory.GetAccessControl();

var rule = new FileSystemAccessRule(windowsAccountUserName,
FileSystemRights.Modify,
InheritanceFlags.None |
InheritanceFlags.ContainerInherit |
InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);

directorySecurity.SetAccessRule(rule);
directory.SetAccessControl(directorySecurity);
return true;

}
#endregion

#region Grant Read Access To Folder
public static bool GrantReadAccessToFolder(string windowsAccountUserName, string folderName)
{

if (String.IsNullOrEmpty(windowsAccountUserName)) return false;
if (String.IsNullOrEmpty(folderName)) return false;
if (!Directory.Exists(folderName)) return false;

var directory = new DirectoryInfo(folderName);
var directorySecurity = directory.GetAccessControl();

var rule = new FileSystemAccessRule(windowsAccountUserName,
FileSystemRights.ReadAndExecute,
InheritanceFlags.None |
InheritanceFlags.ContainerInherit |
InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);


directorySecurity.SetAccessRule(rule);
directory.SetAccessControl(directorySecurity);
return true;

}
#endregion
}

Use .NET To Grant NTFS Access Rights  (2364 Views)