选择的XP机器上的InvalidCastException

时间:2014-08-09 16:36:18

标签: vb.net visual-studio .net-4.0

我遇到的问题是我在某些XP机器上运行的VB.NET中编写的工具。该工具运行正常,并且在具有.NET 4.0.30319.1022的Windows 7和XP计算机上正常运行。

我注意到我遇到麻烦的XP机器是那些没有.NET 4的机器,所以我去安装.NET 4,它安装了.NET 4.0.30319.1。< / p>

这是错误:
http://i.imgur.com/SUHhy8q.png

以下是第86行的代码(86代表For Each):

'_BIOSVer
Dim bios_query As String = "SELECT * FROM " & "Win32_BIOS"
Dim bios_searcher As New ManagementObjectSearcher(bios_query)
For Each info As ManagementObject In bios_searcher.Get()
    _BIOSVer = info.Properties("BIOSVersion").Value.ToString()
Next info

我正在运行.NET 4 Framework的Windows更新,看看是否能解决这个问题,但我想知道你们是否了解发生了什么,或者我的代码是否错误。

更新刚刚完成,重新启动。它运行.NET 4.0.30319.1022但仍然抛出该错误。那么一定是我的代码。

2 个答案:

答案 0 :(得分:1)

BIOS Version返回一个字符串数组(有关详细信息,请查看this link)。

尝试阅读这样的数据

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim BIOSSearcher As New ManagementObjectSearcher("SELECT BIOSVersion FROM Win32_BIOS")
    Dim BIOSVersionInfo() As String = BIOSSearcher.Get(0).Properties("BIOSVersion").Value
    Dim BIOSVersion As String = ""

    If Not BIOSVersionInfo Is Nothing Then
        BIOSVersion = String.Join(vbCrLf, BIOSVersionInfo)
    End If

    MsgBox(BIOSVersion)
End Sub

答案 1 :(得分:1)

有几个问题,但主要是BIOSVersion是一个字符串数组。您可以直接获取返回版本信息的NameCaptionDescription也是如此)。由于你是一件事,你不需要一个循环,但我把它留作模板:

Dim myver As String = ""
Using searcher As New ManagementObjectSearcher("Select Name From Win32_Bios")
    For Each mo As ManagementObject In searcher .Get

        ' EXAMPLE
         'DebugProperties(mo)

        ' no real need to Loop - just for illustration
        For Each pd As System.Management.PropertyData In mo.Properties

            ' if you do SELECT * and want to find something,
            ' compare Pd.Name to the target property 

            ' some things can be nothing.  Such as when a property does not
            ' exist on older systems, so always test:
            If pd.Value IsNot Nothing Then
                myver = pd.Value.ToString
                Exit For
            End If
        Next
    Next

End Using

Return myver

这是一个有用的WMI调试工具,用于显示所有属性名称和值(上面的代码调用了这个注释掉了):

Private Shared Sub DebugProperties(mo As Management.ManagementObject)

    For Each pd As PropertyData In mo.Properties
        If pd.Value IsNot Nothing Then
            Console.WriteLine("{0} {1}", pd.Name,
                              If(pd.Value IsNot Nothing,
                                 pd.Value.ToString,
                                 "Nothing"))
        End If

    Next
End Sub