What's the best way to shut down the computer from a C# program?
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
What's the best way to shut down the computer from a C# program?
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
You can launch the shutdown process:
shutdown -s -t 0
- Shutdownshutdown -r -t 0
- RestartJust to add to Pop Catalin's answer, here's a one liner which shuts down the computer without displaying any windows:
I tried roomaroo's WMI method to shutdown Windows 2003 Server, but it would not work until I added `[STAThread]' (i.e. "Single Threaded Apartment" threading model) to the Main() declaration:
I then tried to shutdown from a thread, and to get that to work I had to set the "Apartment State" of the thread to STA as well:
I'm a C# noob, so I'm not entirely sure of the significance of STA threads in terms of shutting down the system (even after reading the link I posted above). Perhaps someone else can elaborate...?
Different methods:
A.
System.Diagnostics.Process.Start("Shutdown", "-s -t 10");
B. Windows Management Instrumentation (WMI)
C. System.Runtime.InteropServices Pinvoke
D. System Management
After I submit, I have seen so many others also have posted...
Note that shutdown.exe is just a wrapper around InitiateSystemShutdownEx, which provides some niceties missing in ExitWindowsEx
Use shutdown.exe. To avoid problem with passing args, complex execution, execution from WindowForms use PowerShell execute script:
System.Management.Automation.dll should be installed on OS and available in GAC.
Sorry for My english.