c# - 将 WMI CimType 转换为 System.Type

标签 c# wmi type-conversion

我正在尝试编写通用扩展以将 ManagementObjectCollection 转换为 DataTable。这只是为了让我正在编写的启动脚本/程序更容易。我遇到了 CimType 的问题。我已经在下面包含了我到目前为止编写的代码。

    public static DataTable GetData(this ManagementObjectCollection objectCollection)
    {
        DataTable table = new DataTable();

        foreach (ManagementObject obj in objectCollection)
        {
            if (table.Columns.Count == 0)
            {
                foreach (PropertyData property in obj.Properties)
                {
                    table.Columns.Add(property.Name, property.Type);
                }
            }

            DataRow row = table.NewRow();

            foreach (PropertyData property in obj.Properties)
            {
                row[property.Name] = property.Value;
            }

            table.Rows.Add(row);
        }

        return table;
    }
}

我找到了一个我认为可以在 http://www.devcow.com/blogs/adnrg/archive/2005/09/23/108.aspx 上使用的方法.然而,在我看来可能有更好的方法,甚至是我忽略的 .net 功能。

我好像没说清楚。我遇到的问题是我需要从 System.Management.CimType 转换为 System.Type。我几乎认为这是一个常见问题,但我想我正在尝试以一般方式解决它。

最佳答案

您好,您也可以试试下面的代码:

public static class CimConvert
{

private readonly static IDictionary<CimType, Type> Cim2TypeTable =
    new Dictionary<CimType, Type>
        {
            {CimType.Boolean, typeof (bool)},
            {CimType.Char16, typeof (string)},
            {CimType.DateTime, typeof (DateTime)},
            {CimType.Object, typeof (object)},
            {CimType.Real32, typeof (decimal)},
            {CimType.Real64, typeof (decimal)},
            {CimType.Reference, typeof (object)},
            {CimType.SInt16, typeof (short)},
            {CimType.SInt32, typeof (int)},
            {CimType.SInt8, typeof (sbyte)},
            {CimType.String, typeof (string)},
            {CimType.UInt8, typeof (byte)},
            {CimType.UInt16, typeof (ushort)},
            {CimType.UInt32, typeof (uint)},
            {CimType.UInt64, typeof (ulong)}
        };

public static Type Cim2SystemType(this PropertyData data)
{
    Type type = Cim2TypeTable[data.Type];
    if (data.IsArray)
        type = type.MakeArrayType();
    return type;
}

public static object Cim2SystemValue(this PropertyData data)
{
    Type type = Cim2SystemType(data);
    if (data.Type == CimType.DateTime)
        return DateTime.ParseExact(data.Value.ToString(), "yyyyMMddHHmmss.ffffff-000", CultureInfo.InvariantCulture);
    return Convert.ChangeType(data.Value, type);
}
}

关于c# - 将 WMI CimType 转换为 System.Type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2905560/

相关文章:

c# - Azure 移动服务 PullAsync() 未填充同步表

C# - 添加到现有(生成的)构造函数

python - 如何使用 Python 访问不同/远程 Windows 机器?

sql-server - 将海量数据迁移到 SQL

c# - 如何在 Entity Framework 中使用 Date Only 作为数据类型

javascript - 以科学记数法将数字写入 JSON,这样它们就不会被引号括起来

c# - Discord.NET 如何授予用户角色?

c# - 在 PC 上捕获所有音频并将其流式传输到另一台?

powershell - 无法让 WMI 连接在 powershell 中工作

python - 如何在 python 中删除错误类型的行?