Wednesday, June 04, 2008

To shut down a computer in .Net

I was testing something and needed to shutdown a computer. Wanted to look for an example and couldn't found one anywhere. So here is what I have written:


ManagementClass MC = new ManagementClass("Win32_OperatingSystem");
ManagementObjectCollection ObjCol = MC.GetInstances();
//there is only one object in the Collection
foreach (ManagementObject MO in ObjCol)
{
  MO.Scope.Options.EnablePrivileges = true;
  MO.InvokeMethod("Shutdown", null);
}


Note that if you skip the EnablePrivileges line you will get a exception with the message:
Privilege not held

This assumes the identity of the process has the privilege to shutdown the computer under normal conditions.

No comments:

 
Listed on BlogShares