How to start a service in C# on Linux

2019-08-12 18:15发布

问题:

I would like to start a service on my Linux server using a C# console application, through Mono.

public static void StartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}

Would this work?

As an alternative, is there a way to send a command to Linux through C# like you can send it on Windows systems?

I'm trying to start a Linux service using a C# Executable.

回答1:

You can execute a command by doing this;

Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c 'your command here'";
proc.StartInfo.UseShellExecute = false; 
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();


标签: c# linux mono