Per Ryan's suggestion:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.AccessControl;
namespace FileSecurity
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "c:\\temp\\somefile.txt";
Console.WriteLine("Adding access control entry for "
+ fileName);
// Add the access control entry to the file.
AddFileSecurity(fileName, @"SomeFolder\ AnotherFolder",
FileSystemRights.Read, AccessControlType.Deny);
// Add the access control entry to the file.
AddFileSecurity(fileName, @"SomeFolder\AnotherFolder",
FileSystemRights.Write, AccessControlType.Deny);
//Console.WriteLine("Removing access control entry from "
// + fileName);
//// Remove the access control entry from the file.
//RemoveFileSecurity(fileName, @"SomeFolder\AnotherFolder",
// FileSystemRights.ReadData, AccessControlType.Allow);
Console.WriteLine("Done.");
Console.Read();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.Read();
}
}
// Adds an ACL entry on the specified file for the specified account.
public static void AddFileSecurity(string fileName, string account,
FileSystemRights rights, AccessControlType controlType)
{
// Get a FileSecurity object that represents the
// current security settings.
System.Security.AccessControl.FileSecurity fSecurity =
File.GetAccessControl(fileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(account,
rights, controlType));
// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
}
// Removes ACL entry on file for the specified account.
public static void RemoveFileSecurity(string fileName, string
account, FileSystemRights rights, AccessControlType controlType)
{
// Get a FileSecurity object that represents the
// current security settings.
System.Security.AccessControl.FileSecurity fSecurity =
File.GetAccessControl(fileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
rights, controlType));
// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
}
}
}