How can I detect (.NET or Win32) if my application is running in a virtual machine?
This is what I use:
using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
{
using (var items = searcher.Get())
{
foreach (var item in items)
{
string manufacturer = item["Manufacturer"].ToString().ToLower();
if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL"))
|| manufacturer.Contains("vmware")
|| item["Model"].ToString() == "VirtualBox")
{
return true;
}
}
}
}
return false;
Edit 2014-12-02: Updated code so that it no longer detects a Microsoft Surface Pro as a VM. Thanks to Erik Funkenbusch for pointing this out.
Edit 2017-06-29: Updated code so that it also checks the value of the HypervisorPresent
property.
Edit 2018-02-05: removed check for the HypervisorPresent
property since it's incorrect. This property could return true if running on the host O/S on a hyper-V server.