How to detect if my application is running in a virtual machine?

前端 未结 10 1264
青春惊慌失措
青春惊慌失措 2020-11-28 05:52

How can I detect (.NET or Win32) if my application is running in a virtual machine?

10条回答
  •  粉色の甜心
    2020-11-28 06:00

    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.

提交回复
热议问题