using System;
using System.Security.AccessControl;
using System.IO;
public class DirectoryAccessPermissionSetter
{
public static void SetDirectoryAccessPermissionForApplication(string directoryPath, string applicationName)
{
// 獲取目錄信息和安全性信息
DirectoryInfo dInfo = new DirectoryInfo(directoryPath);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// 獲取當前用戶
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
// 創(chuàng)建一個訪問規(guī)則,只允許當前用戶和指定的應用程序訪問
FileSystemAccessRule fsAccessRule = new FileSystemAccessRule(
identity.Name,
FileSystemRights.FullControl,
AccessControlType.Allow,
PropagationFlags.None,
InheritanceFlags.None,
false,
KeywordObjectAccessRule.KeywordObjectAccessRuleType.ObjectAceType
);
// 添加訪問規(guī)則
dSecurity.AddAccessRule(fsAccessRule);
// 再添加一個規(guī)則,拒絕其他所有用戶的訪問
FileSystemAccessRule fsDenyRule = new FileSystemAccessRule(
"BUILTIN\\Users",
FileSystemRights.FullControl,
AccessControlType.Deny,
PropagationFlags.None,
InheritanceFlags.None,
false,
KeywordObjectAccessRule.KeywordObjectAccessRuleType.ObjectAceType
);
dSecurity.AddAccessRule(fsDenyRule);
// 設置新的訪問規(guī)則
dInfo.SetAccessControl(dSecurity);
}
}
// 使用示例
class Program
{
static void Main()
{
string directoryPath = @"C:\MyFolder";
string applicationName = "MyProgram.exe"; // 請確保這個應用程序的名字正確
DirectoryAccessPermissionSetter.SetDirectoryAccessPermissionForApplication(directoryPath, applicationName);
}
}