In this code snippet, you will learn how to Shutdown and Restart a computer using C# managed code. You can easily do so by running the shutdown.exe program using the System.Diagnostics namespace.
How to Restart and Shutdown a computer using C#?
First, add this namespace to your class:
System.Diagnostics
Now, use this function to start or restart your computer. Notice the boolean argument restart which you can use to control the desired action.
void Shutdown(bool restart = false)
{
if (restart)
{
Process.Start("ShutDown", "/r"); // to restart
}
else
{
Process.Start("ShutDown", "/s");// to shutdown
}
}
Timed shutdown using C#
[adinserter block=”2″]You can also use the shutdown command for a timed shutdown. This is useful if you want to shut down your computer after a specific period of time:
Process.Start("shutdown","/s /t 10");
Note: 10 is the time in seconds before the computer shuts down.
Happy coding!
Blog Hero
