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();
// 创建一个访问规则,只允许当前用户和指定的应用程序访问
FileSystemAccessRule fsAccessRule = new FileSystemAccessRule(
identity.Name,
FileSystemRights.FullControl,
AccessControlType.Allow,
PropagationFlags.None,
InheritanceFlags.None,
false,
KeywordObjectAccessRule.KeywordObjectAccessRuleType.ObjectAceType
);
// 添加访问规则
dSecurity.AddAccessRule(fsAccessRule);
// 再添加一个规则,拒绝其他所有用户的访问
FileSystemAccessRule fsDenyRule = new FileSystemAccessRule(
"BUILTIN\\Users",
FileSystemRights.FullControl,
AccessControlType.Deny,
PropagationFlags.None,
InheritanceFlags.None,
false,
KeywordObjectAccessRule.KeywordObjectAccessRuleType.ObjectAceType
);
dSecurity.AddAccessRule(fsDenyRule);
// 设置新的访问规则
dInfo.SetAccessControl(dSecurity);
}
}
// 使用示例
class Program
{
static void Main()
{
string directoryPath = @"C:\MyFolder";
string applicationName = "MyProgram.exe"; // 请确保这个应用程序的名字正确
DirectoryAccessPermissionSetter.SetDirectoryAccessPermissionForApplication(directoryPath, applicationName);
}
}