Search code examples
c#.netservicec#-2.0cacls

How to use CACLS in c# windows service


i want to block certain folder from users, using c# service. that means when you are starting the service though it is blocked or not, the final result is blocked folder. i have writen a code. but the responce is are you sure? please help to solve this

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

Solution

  • You are redirecting the standard input for the CACLS process.
    So you need to feed the process with your input (Like a stream.Writeline("Y");)
    Look at this 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.....