How to start linux systemd service in C# programmatically on Ubuntu Server?

Viewed 402

I have a very simple question: How to start / stop a systemd service from a .NET 6.0 Console App? Just to clarify: I do not want the service to stop itself. I want a console app to stop another service already installed on a Ubuntu Server 20.04.

More concrete: How would I call this line in C# properly?

sudo systemctl start SERVICE_NAME

Do I have to start a Process like this?

var process = new Process();
process.StartInfo.FileName = " /usr/lib/systemd"
process.StartInfo.Arguments = "start SERVICENAME";
process.Start(); 

What have I tried so far?

I googled but could not find any viable solution, and since I am no expert on Linux I might have fallen into the XY trap

1 Answers

I've never done this before. I like .NET and I use netcore every day but, if you want to create a script to be run only on linux. Maybe a bash script would do.

Since you want to use .NET, I think you'll need to do something like:

ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = "/bin/bash", Arguments = "systemctl stop SERVICE", }; 
Process proc = new Process() { StartInfo = startInfo, };
proc.Start();

You're creating a bash instance from where you call systemctl.

You also might want to wait until the process has finished. You can do that with

proc.WaitForExit();

Be aware this is a synchronous waiting.

Related