7

I have a program in Debian which needs root privileges and myuser has to run it, but I have to do the call from a .NET application (C#) running in mono. In /etc/sudoers, I have add the line:

myuser ALL = NOPASSWD: /myprogram

so sudo ./myprogram works for myuser.

In. NET I use in my code

string fileName = "/myprogram";
ProcessStartInfo info = new ProcessStartInfo (fileName);
...

How can I do the call "sudo fileName"? It doesn't work by the time... thank you, Monique.

jariq
  • 11,681
  • 3
  • 33
  • 52
Mon
  • 131
  • 2
  • 4

2 Answers2

12

The following worked for me in a similar situation, and demonstrates passing in multiple arguments:

var psi = new ProcessStartInfo
{
    FileName = "/bin/bash",
    UseShellExecute = false,
    RedirectStandardOutput = true,
    Arguments = string.Format("-c \"sudo {0} {1} {2}\"", "/path/to/script", "arg1", arg2)
};

using (var p = Process.Start(psi))
{
    if (p != null)
    {
        var strOutput = p.StandardOutput.ReadToEnd();
        p.WaitForExit();
    }
}
SteveChapman
  • 3,051
  • 1
  • 22
  • 37
  • Great way to capture stdout too - `RedirectStandardOutput = true` doesn't work with Jariq's answer. – Dunc Aug 31 '15 at 10:33
2

You just need to pass your program as the argument to the sudo command like this:

ProcessStartInfo info = new ProcessStartInfo("sudo", "/myprogram");
Process.Start(info);
jariq
  • 11,681
  • 3
  • 33
  • 52