I am using the below Method to apply permission
private bool SetPermission(string applyPath)
{
try
{
DirectoryInfo IsRootAvailable = new DirectoryInfo(applyPath);
if (IsRootAvailable.Exists)
{
WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
FileSystemRights Rights = (FileSystemRights)0;
Rights = FileSystemRights.Modify;
FileSystemAccessRule AccessRule = new FileSystemAccessRule("NETWORK SERVICE", Rights,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow);
DirectoryInfo Info = new DirectoryInfo(applyPath);
DirectorySecurity Security = Info.GetAccessControl(AccessControlSections.Access);
bool Result = false;
Security.ModifyAccessRule(AccessControlModification.Set, AccessRule, out Result);
if (!Result)
{
rtxtConfirmMessage.Text += string.Format("\t\t\t--\t{0}", "Failed.");
return false;
}
InheritanceFlags iFlags = InheritanceFlags.ObjectInherit;
iFlags = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
AccessRule = new FileSystemAccessRule("NETWORK SERVICE", Rights,
iFlags,
PropagationFlags.InheritOnly,
AccessControlType.Allow);
Result = false;
Security.ModifyAccessRule(AccessControlModification.Add, AccessRule, out Result);
if (!Result)
{
rtxtConfirmMessage.Text += string.Format("\t\t\t--\t{0}", "Failed.");
return false;
}
Info.SetAccessControl(Security);
return true;
}
else
return false;
}
catch (Exception ex)
{
rtxtConfirmMessage.Text += string.Format("\t\t\t--\t{0}", "Failed." + ex.Message);
return false;
}
}
and a help from MSDN
FileSystemAccessRule Class[
^] has the below code
using System;
using System.IO;
using System.Security.AccessControl;
namespace FileSystemExample
{
class FileExample
{
public static void Main()
{
try
{
string fileName = "test.xml";
Console.WriteLine("Adding access control entry for "
+ fileName);
AddFileSecurity(fileName, @"DomainName\AccountName",
FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Removing access control entry from "
+ fileName);
RemoveFileSecurity(fileName, @"DomainName\AccountName",
FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Done.");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static void AddFileSecurity(string fileName, string account,
FileSystemRights rights, AccessControlType controlType)
{
FileSecurity fSecurity = File.GetAccessControl(fileName);
fSecurity.AddAccessRule(new FileSystemAccessRule(account,
rights, controlType));
File.SetAccessControl(fileName, fSecurity);
}
public static void RemoveFileSecurity(string fileName, string account,
FileSystemRights rights, AccessControlType controlType)
{
FileSecurity fSecurity = File.GetAccessControl(fileName);
fSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
rights, controlType));
File.SetAccessControl(fileName, fSecurity);
}
}
}