GetExpandedStringValue: Type Mismatch

This is another post about time painfully spent trying to solve a simple bug.

I'm currently migrating a lot of VBScript code to a VB.NET application. Before you email me about how I should be using C#, please take note that migrating code is already tricky enough as it is so I decided for a language that shares a lot of syntactic similarities with VBScript.

Back to the bug, I was migrating this VBScript code:


Const C_HKEY_LOCAL_MACHINE = 2147483650
Dim Server
Dim strValue
Dim objReg
Dim strKeyPath
Server = "localhost"
strValue = ""

Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & Server & "\root\default:StdRegProv")
strKeyPath = "SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName"

If objReg.GetExpandedStringValue(C_HKEY_LOCAL_MACHINE, strKeyPath, "ComputerName", strValue) <> 0 Then
Error ("error reading registry")
End If


Well, not actually this code but something like this. This works in VBScript but this code in VB.NET that compiles and seems quite the same, generates a "Type mismatch" exception:


Const C_HKEY_LOCAL_MACHINE = 2147483650
Dim Server
Dim strValue
Dim objReg
Dim strKeyPath
Server = "localhost"
strValue = ""

objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & Server & "\root\default:StdRegProv")
strKeyPath = "SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName"

If objReg.GetExpandedStringValue(C_HKEY_LOCAL_MACHINE, strKeyPath, "ComputerName", strValue) <> 0 Then
Error ("error reading registry")
End If


After wasting a lot of time reading forums and tweaking the GetExpandedStringValue arguments and reading it's documentation, I finally fixed it replacing
Const C_HKEY_LOCAL_MACHINE = 2147483650
with
Const C_HKEY_LOCAL_MACHINE = &H80000002


The final fixed code would be something like this:


Const C_HKEY_LOCAL_MACHINE = &H80000002
Dim Server
Dim strValue
Dim objReg
Dim strKeyPath
Server = "localhost"
strValue = ""

objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & Server & "\root\default:StdRegProv")
strKeyPath = "SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName"

If objReg.GetExpandedStringValue(C_HKEY_LOCAL_MACHINE, strKeyPath, "ComputerName", strValue) <> 0 Then
Error ("error reading registry")
End If




You might also run into this problem, off-course, with functions like GetStringValue or EnumValues.

Comments

Popular posts from this blog

Missing Win32_Product

Samsung CLP-300

HP laptop problems (PART 1)