Page Not Found

Sorry, that page does not exist. Go Home, Search or give up and read the random post below:

 

 

Reboot computer in C# / .NET

Updated on Monday, May 2, 2022

Reboot computer in C# / .NET

.NET doesn’t support rebooting, logging off or shutting down your computer though a managed API. Searching for the best way to do this brings up three options: WMI, shutdown.exe and ExitWindowsEx.

I regard WMI as the last resort of the desperate. Weakly typed magic string juju.

Calling Process.Start(“shutdown.exe /r /t 0”) might work, but how would you know? And you’ve got the overheard of starting a new process just to accomplish a reboot. Lazy.

The best way to reboot is P/Invoke to ExitWindowsEx. Unfortunately there’s some really awful sample code out there which will either fail to do anything or mask any errors. I’ve included a drop-in class below that fixes these problems.

If you read all the way through the documentation for ExitWindowsEx you’ll find this:

To shut down or restart the system, the calling process must use the AdjustTokenPrivileges function to enable the SE_SHUTDOWN_NAME privilege. For more information, see Running with Special Privileges.

So just calling ExitWindowsEx won’t do anything. The sample code below adjusts the process token and then reboots (change the flags passed to ExitWindowsEx to shutdown instead, or to pass in a different reason). You’ll also get a Win32Exception if a failure occurs. Catch this, and you can tell the user that they need to reboot manually.

Add your comment...

Related Posts

You Might Also Like

(All Code Posts)

(Published to the Fediverse as: Reboot computer in C# / .NET #code #reboot #wmi #shutdown.exe #exitwindowsex #openprocesstoken #lookupprivilegevalue How to call ExitWindowsEx correctly to reboot a computer in C# / .NET including error handline in case you need to tell the user to reboot manually. )