gpt4 book ai didi

c# - 如何使用 C# 获取电池健康状况

转载 作者:行者123 更新时间:2023-11-30 16:59:09 26 4
gpt4 key购买 nike

我正在尝试获取两个值,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:?

最佳答案

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

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);
}
}
}
}
}

关于c# - 如何使用 C# 获取电池健康状况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24192912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com