Is it possible to restart a PC using "pure" .NET and *without* using p/invoke?
Is it possible, without employing pinvoke, to restart a PC using .NET?
I kind of just repeated the title, but I'm not too sure how to elaborate much further!
Edit:
I should have mentioned that don't want to use "shutdown -r" as a solution.
I was really after a pure .NET way, something like:
Environment.ShutDown();
In other words, something that is maintained with .NET as new versions of Windows arise.
Edit 2:
Please stop asking "what's wrong with p/invoke". Those sort of answers are exactly what SO users seem to love; the supposed "lateral" approach to answering a question. However, although there is no real problem with p/invoke and I will happily use it, what on earth is wrong with asking if .NET has a more official way of achieving something? If it's in .NET then any AP开发者_运维知识库I changes between OSes will (most likely) get reflected. Whatever the reason, it's not a crime to seek to minimise DLL import usage is it?
I'm sure if I included something in a question like:
[DllImport("something32.dll")]
static extern int ClimbWall32Ex(IntPtr32 blah);
And you could just do:
SomeNamespace.ClimbWall();
Everyone one here would scream: "what is wrong with using SomeNamespace.ClimbWall();
??"
Sigh.
Not sure why you wouldn't just use P/Invoke, but one alternate way of restarting would be to use System.Diagnostics.Process.Start
in conjunction with the shutdown
command.
Example:
System.Diagnostics.Process.Start("shutdown", "-r");
If that also isn't acceptable, you could look into using WMI (see here for an example that could probably be modified to suit your purposes).
You can use WMI to restart. Below is from memory, but I think it is pretty close, although a little sloppy. :)
var computer = "COMPUTERNAME";
var query = string.Format("SELECT * FROM Win32_OperatingSystem");
ManagementScope scope;
var computerPath = string.Format(@"\\{0}\root\cimv2", computer);
scope = new ManagementScope(computerPath);
scope.Connect();
var q = new ObjectQuery(query);
var s = new ManagementObjectSearcher(scope, q);
ManagementObjectCollection qr;
qr = s.Get();
foreach (ManagementObject r in qr)
{
string[] p = { "" };
r.InvokeMethod("Reboot", p);
}
You need to call ExitWindowsEx which is only available through DllImport
精彩评论