1

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");
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
lankitha
  • 283
  • 7
  • 15

2 Answers2

6

Don't call the command line cacls utility, instead use the .NET API to change permissions. Invoking command line utilities should always be seen as a last workaround for performing tasks. It is much better to access an API directly that is meant for programmatic access.

  • Directory.GetAccessControl(string) gets the current ACL.
  • Directory.SetAccessControl(string, DirectorySecurity) sets the ACL.

Generally when working with ACLs it's better to work only with granting rights and not use deny flags at all. Denying BUILTIN\Users is very broad and that deny will overrule any grant made to any user. It is better to construct an ACL that does not grant any rights to normal users and only give rights to the specific users that should have access.

Anders Abel
  • 67,989
  • 17
  • 150
  • 217
1

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.....
Steve
  • 213,761
  • 22
  • 232
  • 286