.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.
Personal Finger Daemon for Windows — Did you know that Windows still has a vestigial finger command with just about nothing left to talk to? One of my New Year's resolutions is to bring finger back and unlike the stalled webfinger project I need to make some progress. Here's some C#...
Scanning from the ADF using WIA in C# — I've been going nuts trying to scan from the document feeder on my Canon imageClass MF4150. Everything worked as expected from the flatbed, no dice trying to persuade the ADF to kick in. I found some sample code but it was oriented towards...
Crushing PNGs in .NET — I'm working on page speed and Google PageSpeed Insights is telling me that my PNGs are just way too large. Sadly .NET does not provide any way to optimize PNG images so there is no easy fix - just unmanaged libraries and command line tools....