1

我想使用 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");
}
4

2 回答 2

6

不要调用命令行cacls实用程序,而是使用 .NET API 来更改权限。调用命令行实用程序应始终被视为执行任务的最后一种解决方法。直接访问用于编程访问的 API 要好得多。

  • Directory.GetAccessControl(string)获取当前 ACL。
  • Directory.SetAccessControl(string, DirectorySecurity)设置 ACL。

通常,在使用 ACL 时,最好只使用授予权限而不使用拒绝标志。拒绝BUILTIN\Users的范围非常广泛,拒绝将推翻对任何用户的任何授权。最好构造一个不授予普通用户任何权限的 ACL,只授予应该有权访问的特定用户的权限。

于 2012-03-08T08:23:12.523 回答
1

您正在重定向 CACLS 进程的标准输入。
所以你需要用你的输入来提供这个过程(就像一个stream.Writeline(“Y”);)
看看这个来自MSDN的样本

StreamWriter myStreamWriter = myProcess.StandardInput;
myStreamWriter.Writeline("Y"); // Could it be localized ??? -->Oui, Ja, Sì etc...
myStreamWriter.Close();  // This seems to be is important.....
于 2012-03-08T08:21:04.770 回答