How to shutdown or restart the computer using C# or VB.NET
Suppose you have written an application that does processing, and at the end of the processing, it should shut the PC down so you can go off to bed and not have to wait for it to complete. I have applications like that to upload and download from the website.
To shut down the computer is easy. You shell out to the shutdown application rather than calling any system libraries.
public static void Shutdown(bool bForce, bool bRestart)
{
string sCmd = "";
if(bForce==true)
sCmd = "/f ";
if(bRestart == true)
sCmd += "/r ";
System.Diagnostics.Process.Start("ShutDown", sCmd);
}
You can extend the above function to include other parameters that the shutdown command supports, but the above is just a starting point.
For a list of all the additional parameters that you can pass to it, I would suggest you open a command prompt and type:-
shutdown -?
It should be pointed out that the program you create must be started with Administrator rights. Otherwise, the shutdown will not happen.
Although I said C#, If you need the code in VB.NET, see below. Translated using Telerik.
Public Shared Sub Shutdown(ByVal bForce As Boolean, ByVal bRestart As Boolean)
Dim sCmd As String = ""
If bForce = True Then sCmd = "/f "
If bRestart = True Then sCmd += "/r "
System.Diagnostics.Process.Start("ShutDown", sCmd)
End Sub
Tags - .NET
Last Modified : June 2023