如何使用c#获取电池健康状态

本文关键字:健康 状态 获取 何使用 | 更新日期: 2023-09-27 18:08:28

我试图获得两个值,DesignCapacityFullChargeCacity,但它们没有返回值。

我使用下面的代码:

public static bool CheckBattery()
{
    bool _testResult = false;
    string computer = ".";
    try
    {
        ManagementScope scp = new ManagementScope(@"''" + computer + @"'root'cimv2");
        scp.Connect();
        SelectQuery sql = new SelectQuery("CIM_Battery");
        ManagementObjectSearcher mos = new ManagementObjectSearcher(scp,sql);
        ManagementObjectCollection moc = mos.Get();
        List<string> resultList = new List<string>();
        foreach (ManagementObject o in moc)
        {
            foreach (PropertyData property in o.Properties)
            {
                resultList.Add( property.Name + ":" +property.Value);
            }
            File.WriteAllLines("bat.txt", resultList.ToArray());
            //UInt16 availability = (UInt16)o["Availability"];
            //resultList.Add("Availability," + availability.ToString());
            //UInt16 batterystatus = (UInt16)o["BatteryStatus"];
            //resultList.Add("BatteryStatus," + batterystatus.ToString());
            //string status = (string)o["Status"];
            //resultList.Add("Status," + status);
            //UInt32 Desigcap = (UInt32)o["DesignCapacity"];
        }
    }
    catch (Exception ex)
    {
        string errr = ex.Message;
    }
    return _testResult;
}

如何避免在此属性中获得空值?实际上,迭代对象得到以下信息:

Availability:2
BatteryRechargeTime:
BatteryStatus:2
Caption:Internal Battery
Chemistry:2
ConfigManagerErrorCode:?
ConfigManagerUserConfig:?
CreationClassName:Win32_Battery
Description:Internal Battery
DesignCapacity:?
DesignVoltage:17119
DeviceID:3338SANYO AL12A32
ErrorCleared:?
ErrorDescription:?
EstimatedChargeRemaining:100
EstimatedRunTime:71582788
ExpectedBatteryLife:
ExpectedLife:?
FullChargeCapacity:?
InstallDate:?
LastErrorCode:
MaxRechargeTime:
Name:AL12A32
PNPDeviceID:
PowerManagementCapabilities:System.UInt16[]
PowerManagementSupported:False
SmartBatteryVersion:
Status:OK
StatusInfo:?
SystemCreationClassName:Win32_ComputerSystem
SystemName:MX02L180
TimeOnBattery:?
TimeToFullCharge:?

如何使用c#获取电池健康状态

要获得这些特定的值,您需要对不同的类执行单独的查询。

DesignCapacity可从BatteryStaticData

查询

FullChargeCacity可从BatteryFullChargedCapacity

查询

您还需要在代码中为查询使用不同的作用域。这些类出现在root/WMI而不是root/cimv2

string scope = "root/WMI";
string query = "SELECT DesignedCapacity FROM BatteryStaticData";
using (ManagementObjectSearcher batteriesQuery = new ManagementObjectSearcher(scope, query))
{
    using (ManagementObjectCollection batteries = batteriesQuery.Get())
    {
        foreach (ManagementObject battery in batteries)
        {
            if (battery != null)
            {
                foreach (var property in battery.Properties)
                {
                    Console.Log("Property name: " + property.Name + " Property value: " + property.Value);
                }
            }
        }
    }
}