Csharp/C Sharp by API/System.Security.AccessControl/FileSecurity
FileSecurity.AddAccessRule
using System;
using System.IO;
using System.Security.AccessControl;
class MainClass {
static void Main(string[] args) {
FileStream stream;
string fileName;
fileName = Path.GetRandomFileName();
using (stream = new FileStream(fileName, FileMode.Create)) {
// Do something.
}
SetRule(fileName, "Everyone", FileSystemRights.Read, AccessControlType.Deny);
try {
stream = new FileStream(fileName, FileMode.Create);
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
} finally {
stream.Close();
stream.Dispose();
}
}
static void AddRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType) {
FileSecurity fSecurity = File.GetAccessControl(filePath);
fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
File.SetAccessControl(filePath, fSecurity);
}
static void SetRule(string filePath, string account, FileSystemRights rights, AccessControlType controlType) {
FileSecurity fSecurity = File.GetAccessControl(filePath);
fSecurity.ResetAccessRule(new FileSystemAccessRule(account, rights, controlType));
File.SetAccessControl(filePath, fSecurity);
}
}
FileSecurity.ResetAccessRule
using System;
using System.IO;
using System.Security.AccessControl;
static class MainClass
{
static void Main(string[] args)
{
FileStream stream = null;
string fileName = "c:\\test.txt";
// Deny "Everyone" access to the file
FileSecurity fSecurity = File.GetAccessControl(fileName);
fSecurity.ResetAccessRule(new FileSystemAccessRule("Everyone",FileSystemRights.Read, AccessControlType.Deny));
File.SetAccessControl(fileName, fSecurity);
// Attempt to access file.
try
{
stream = new FileStream(fileName, FileMode.Create);
}
catch (Exception ex)
{
Console.WriteLine("Exception thrown: ");
Console.WriteLine(ex.ToString());
}
finally
{
stream.Close();
stream.Dispose();
}
}
}