?
Solved

How can i read and write to registry from VB.net

Posted on 2005-04-15
9
Medium Priority
?
292 Views
Last Modified: 2011-09-20
I am looking for some code which does the folowing

a) read a specified registry key
b) write a value to a specific key
c) check if a key exists
d) create a new key

0
Comment
Question by:AlexPonnath
9 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 13790139
0
 
LVL 25

Assisted Solution

by:RonaldBiemans
RonaldBiemans earned 400 total points
ID: 13790184
From MSDN, If you just type registry in the help you will find all you need

Imports Microsoft.Win32
Dim regVersion As RegistryKey
Dim keyValue As String
keyValue = "Software\\Microsoft\\TestApp\\1.0"
regVersion = Registry.CurrentUser.OpenSubKey(keyValue, False)
Dim intVersion As Integer = 0
If (Not regVersion Is Nothing) Then
    intVersion = regVersion.GetValue("Version", 0)
    regVersion.Close()
End If
The following example reads, increments, and then writes a DWORD value to HKEY_CURRENT_USER:
Imports Microsoft.Win32
Dim regVersion As RegistryKey
regVersion =
Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0", True)
If regVersion Is Nothing Then
    ' Key doesn't exist; create it.
    regVersion =
Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0")
End If

Dim intVersion As Integer = 0
If (Not regVersion Is Nothing) Then
    intVersion = regVersion.GetValue("Version", 0)
    intVersion = intVersion + 1
    regVersion.SetValue("Version", intVersion)
    regVersion.Close()
End If
0
 

Author Comment

by:AlexPonnath
ID: 13790311
Ok something is missing here..

i am using the code from the link provided, except i placed it in a module when i try to compile i get an error for
C:\Documents and Settings\Administrator.ICCINET\My Documents\Visual Studio Projects\LIBD\customeLookup.vb(62): 'LocalMachine' is not a member of 'LIBD.registry'.

any idea what i am missing ?

Imports Microsoft.Win32

Module registry
    Public Function createKey()
        Dim regKey As RegistryKey
        regKey = registry.LocalMachine.OpenSubKey("SOFTWARE", True)
        regKey.CreateSubKey("MyApp")
        regKey.Close()
        MsgBox("Registry key HKLM\Software\MyApp created.")
End Function
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 12

Assisted Solution

by:S-Twilley
S-Twilley earned 800 total points
ID: 13790381
You may find it more convenient to write your own functions to perform those common tasks... that way you can pass a registrykey relating to the main key and a string which relates to the sub registrykey ... which means you don't have to keep choosing between the different key classes e.g.  CurrentUser, ClassesRoot...

Some pseudo-code

Sub WriteValueToRegistry(ByVal TopKey As RegistryKey, ByVal SubKey As String, ByVal ValueName As String, ByVal NewValue As Object)
        Dim keySub As RegistryKey = TopKey.OpenSubKey(SubKey)
        keySub.SetValue(ValueName, NewValue)
End Sub

=-=-=-=-

obviously you may want to put more testing in there... to catch errors

alternatively... you could combine the TopKey and SubKey (and possibly even the ValueName) into one string, and pass that to the sub... and then split it

Sub WriteValueToRegistry(ByVal FullPath As String, ByVal NewValue As Object)
        Dim firstPos As Integer = FullPath.IndexOf("\")

        If firstPos >= 0 Then
              Dim subKey As String = ""
              Dim valueName as string = ""
              Dim mainKey As String = FullPath.SubString(0,firstPos)
              FullPath = FullPath.SubString(firstPos+1)

              firstPos = FullPath.IndexOf("\")

              If firstPos >= 0 Then
                   subKey = FullPath.SubString(0,firstPos)
                   valueName = FullPath.SubString(firstPos+1)
              Else
                   valueName = FullPath
              End If

              Dim thisKey As RegistryKey

              Select Case mainKey.ToLower
                   Case "HKEY_CLASSES_ROOT"
                          thisKey = ClassesRoot

                   '....  do the rest of the cases for the different main keys

               End Select

               if  subKey.Length > 0 then
                      thisKey = thisKey.OpenSubKey(subKey, True)
               End If

               thisKey.SetValue(valueName, NewValue)

               if  subKey.Length > 0 then
                      thisKey.Close
               End If
         End If
      End Sub

=======================

This was written straight into here, but I think I've done it right... at the moment it doesn't take into account writing the default value to a Key ... the way you'd call this would be something like:

WriteValueToRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\MyApp", "C:\MySoftware\MyApp.exe")

Least that's the plan...  let me know if I typed all that out wrong! :P


0
 
LVL 53

Expert Comment

by:Dhaest
ID: 13790397
Do you have the rights to access the registry ?
Does you subKey exist ?
0
 
LVL 13

Expert Comment

by:Torrwin
ID: 13790979
That seems overly complicated, here is how I do it:

SaveSetting("APPLICATION_NAME", "FOLDER_NAME", "File_Name", "VALUE_YOU_WANT_STORED")

GetSetting("APPLICATION_NAME, "FOLDER_NAME", "File_Name", "")

DeleteSetting(APPLICATION_NAME, "FOLDER_NAME")

These values will be stored in the registry under "My Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings"
0
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13791020
Well the code samples given have been to access anywhere in the registry... hence the "complication"
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 13792214
0
 
LVL 14

Accepted Solution

by:
amyhxu earned 800 total points
ID: 13801874
a) read the key, get the value

        Dim cKey As Microsoft.Win32.RegistryKey
        cKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\appName")

        Dim DefaultValue As Integer = someValue ' Set default value for the key according to the value type you define for the key, I use Integer for example
        If (Not cKey Is Nothing) Then
            Dim keyVal As Integer = cKey.GetValue("keyName", DefaultValue)
            cKey.Close()
        Else
            ' some code in case the registry key does not exist
        End If


b), c), d) together -- when I write a value to registry key, I check if it exists, if not, create the key first:

        Dim cKey As Microsoft.Win32.RegistryKey
        cKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\appName", True)

        ' Check if key not exists, create the key
        If (cKey Is Nothing) Then
            cKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("Software\appName")
        End If
       
        ' Write value to the key
        If (Not cKey Is Nothing) Then
            cKey.SetValue("keyName", keyValue)
            cKey.Close()
        End If
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses
Course of the Month15 days, 10 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question