2012-03-08 32 views
1

我想用c#服務阻止用戶的某個文件夾。這意味着當您啓動服務時雖然它被阻止,但最終結果是阻止的文件夾。我寫了一個代碼。但回覆是你確定嗎?請幫忙解決這個如何在C#窗口服務中使用CACLS

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"); 
} 

回答

1

您重定向爲CACLS進程的標準輸入。
所以,你需要與你輸入到輸入過程(像stream.Writeline(「Y」);)
看這個sample from MSDN

StreamWriter myStreamWriter = myProcess.StandardInput; 
myStreamWriter.Writeline("Y"); // Could it be localized ??? -->Oui, Ja, Sì etc... 
myStreamWriter.Close(); // This seems to be is important..... 
+0

我試了p.StandardInput.WriteLine(「Y」);和你的方法,都不會工作 – lankitha 2012-03-08 09:21:35

+0

我已經更新了我的答案 – Steve 2012-03-08 09:29:10

5

不要調用命令行實用cacls,而是使用.NET API來更改權限。調用命令行實用程序應始終被視爲執行任務的最後一個解決方法。直接訪問用於編程式訪問的API會更好。

  • Directory.GetAccessControl(string)獲取當前ACL。
  • Directory.SetAccessControl(string, DirectorySecurity)設置ACL。

通常在使用ACL時,最好只使用授予權限而不使用拒絕標誌。否認BUILTIN\Users是非常寬泛的,否認將否決任何授予任何用戶的授權。最好構建一個不授予普通用戶任何權限的ACL,只給予應該有權訪問的特定用戶權限。