To set file permissions or AccessControl Lists (ACLs) in C#, you use classes from the
System.Security.AccessControl namespace.
Example: Grant Read and Write Permissions to a Specific User
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
public class FilePermissionHelper
{
public static void SetFilePermissions(string filePath, string userName)
{
FileSecurity fileSecurity = File.GetAccessControl(filePath);
// Create a new rule granting read and write access
FileSystemAccessRule accessRule = new FileSystemAccessRule(
userName,
FileSystemRights.Read | FileSystemRights.Write,
AccessControlType.Allow
);
// Add the rule and apply it
fileSecurity.AddAccessRule(accessRule);
File.SetAccessControl(filePath, fileSecurity);
}
}
Usage
string file = @"C:\secure\file.txt";
string user = @"DOMAIN\UserName"; // or use Environment.UserName
FilePermissionHelper.SetFilePermissions(file, user);
Key Concepts
Class
Purpose
FileSecurity
Represents the ACL for a file
FileSystemAccessRule
Defines access rules (who, what rights)
AccessControlType
Allow or Deny
FileSystemRights
Enum for specific rights (e.g. Read, Write, Modify, FullControl)
To Remove or Modify Permissions
Use RemoveAccessRule, ResetAccessRule, or SetAccessRule on the
FileSecurity object.
Notes
Your application needs permission to change ACLs (run as administrator if needed).
Works on NTFS file systems where ACLs are supported.
Use DirectorySecurity and Directory.SetAccessControl for folders.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To set file permissions or Access Control Lists (ACLs) in C#, you use classes from the
System.Security.AccessControlnamespace.Example: Grant Read and Write Permissions to a Specific User
Usage
Key Concepts
FileSecurityFileSystemAccessRuleAccessControlTypeAlloworDenyFileSystemRightsTo Remove or Modify Permissions
Use
RemoveAccessRule,ResetAccessRule, orSetAccessRuleon theFileSecurityobject.Notes
DirectorySecurityandDirectory.SetAccessControlfor folders.