我想使用 C# 服务阻止用户访问某些文件夹。这意味着当您启动服务时,无论是否被阻止,最终结果都是被阻止的文件夹。我写了一个代码。但回复是你确定吗?请帮忙解决这个问题
string Pathname = folder;
EventLog.WriteEntry(Pathname);
string Username = @"BUILTIN\Users";
string UserRights = "N";
if (Pathname == null || Pathname == "")
{
EventLog.WriteEntry("No File");
}
string CommandLine = '"' + System.IO.Path.GetFullPath(Pathname) + '"' + " /C ";
CommandLine += @" /T ";
CommandLine += @" /P " + Username + ":" + UserRights;
Process p = new Process();
p.StartInfo.FileName = "cacls.exe";
p.StartInfo.Arguments = CommandLine;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
p.StartInfo.CreateNoWindow = true;
p.Start();
string Response = p.StandardOutput.ReadToEnd();
EventLog.WriteEntry(Response);
if (Response == null || Response == "")
{
EventLog.WriteEntry("Error");
}
最佳答案
不要调用命令行 cacls
实用程序,而是使用 .NET API 来更改权限。调用命令行实用程序应始终被视为执行任务的最后一种解决方法。直接访问用于编程访问的 API 会好得多。
Directory.GetAccessControl(string)
获取当前 ACL。Directory.SetAccessControl(string, DirectorySecurity)
设置 ACL。
通常,在使用 ACL 时,最好只使用授予权限而不使用拒绝标志。拒绝BUILTIN\Users
的范围非常广泛,拒绝将否决对任何 用户的任何授权。最好构造一个ACL,不授予普通用户任何权限,只授予应该访问的特定用户权限。
关于c# - 如何在 C# Windows 服务中使用 CACLS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9614561/