c# - 如何在 C# Windows 服务中使用 CACLS

标签 c# .net service c#-2.0 cacls

我想使用 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/

相关文章:

symfony - Symfony2 服务的外观模式

Android如何等到服务实际连接?

c# - .NET Web Api 2.1 中 Ninject 绑定(bind)的无参数构造函数错误

c# - 是否有可能诱使此 WindowsIdentity 代码使用错误的用户?

c# - 好的类(class)名称的想法

.net - 如何在 Windows 中从非托管 C++ 代码调用托管 .NET 代码,反之亦然?

c# - 使用 JSON 的 WCF RESTful POST,来自 Windows 应用商店应用

c# - 这个 List<string> ListName 作为参数?

c# - XNA 4 和外部引用

mysql - 我需要比较 MySql 中的 2 个表并显示差异