Reading and Writing to the Registry in VB.NET is fairly simple, especially when compared to using C++. However, it can still be a little difficult to get going. Here are 3 functions to perform the basic Registry operations: Read, Write, and Delete.
Examples Using the Functions:
Dim value As String = _
GetRegistryValue(Registry.LocalMachine, _
"SOFTWARE\CompanyName\ApplicationName", "License")
SetRegistryValue(Registry.LocalMachine, _
"SOFTWARE\CompanyName\ApplicationName", _
"License", "value")
DeleteRegistryValue(Registry.LocalMachine, _
"SOFTWARE\CompanyName\ApplicationName", "License")
Read a Registry Value
Public Function GetRegistryValue(ByVal regKey As RegistryKey, _
ByVal subKey As String, ByVal valueName As String) As String
Dim value As String = ""
Dim registryKey As RegistryKey = regKey
Dim registrySubKey As RegistryKey
registrySubKey = registryKey.OpenSubKey(subKey)
If registrySubKey IsNot Nothing Then
Try
value = registrySubKey.GetValue(valueName).ToString
Catch ex As Exception
value = ""
End Try
registrySubKey.Close()
End If
Return value
End Function
Write a Registry Value
Public Function SetRegistryValue(ByVal regKey As RegistryKey, _
ByVal subKey As String, ByVal valueName As String, ByVal value As String) As Boolean
Dim registryKey As RegistryKey = regKey
Dim registrySubKey As RegistryKey
registrySubKey = registryKey.OpenSubKey(subKey, True)
If registrySubKey Is Nothing Then
registrySubKey = registryKey.CreateSubKey(subKey, RegistryKeyPermissionCheck.ReadWriteSubTree)
End If
If registrySubKey IsNot Nothing Then
registrySubKey.SetValue(valueName, value)
registrySubKey.Close()
Return True
End If
Return False
End Function
Delete a Registry Value
Public Function DeleteRegistryValue(ByVal regKey As RegistryKey, _
ByVal subKey As String, ByVal valueName As String) As Boolean
Dim value As String = ""
Dim registryKey As RegistryKey = regKey
Dim registrySubKey As RegistryKey
registrySubKey = registryKey.OpenSubKey(subKey, True)
If registrySubKey IsNot Nothing Then
Dim retValue As Boolean = True
Try
registrySubKey.DeleteValue(valueName)
Catch ex As Exception
retValue = False
End Try
registrySubKey.Close()
Return retValue
End If
Return False
End Function
1 comment:
sweet. Nice blog by the way.
CB - C.S.E.
Post a Comment