簡體   English   中英

如何在C#Windows Service中使用CACLS

[英]How to use CACLS in c# windows service

我想使用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,該ACL不向普通用戶授予任何權限,而僅向應具有訪問權限的特定用戶授予權限。

您正在重定向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.....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM