Reboot computer in C# / .NET

By Robert Ellison. 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

(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. )

Comments

Dave

FYI, it looks like the embedded gist and its link get blocked by (some) corporate firewalls. I had to view on personal hardware.

Robert Ellison

Hi Massimo, there should be an embedded GIST in the post above. If that is failing to load for you then try here.

Massimo

where is the code?

Add Comment

All comments are moderated. Your email address is used to display a Gravatar and optionally for notification of new comments and to sign up for the newsletter.