28 abr 2009

Como leer y escribir en el Registro de Windows desde una aplicación .NET

Para trabajar sobre el registro de Windows utilizaremos las cases Registry y RegistryKey del Namespace Microsoft.Win32. Con éstas 2 clases podremos realizar todas tareas de lectura y escritura en el registro.
Este es un ejemplo muy sencillo, por lo tanto vamos a crear una clave Key, dentro crearemos un valor Value luego los eliminaremos. Después leeremos todos los Values que se encuentren en HKLM\Microsoft\Windows\CurrentVersion\Run, que son los que indican qué aplicaciones se ejecutan al iniciar Windows para todos los usuarios.

Debajo de estas líneas está el código, uno de los ejemplos más sencillos para leer y escribir en el Registro de Windows.

Trabajar con el Registro de Windows en nuestra aplicación .NET


Imports Microsoft.Win32
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CrearKey()
End Sub

Private Sub CrearKey()
Dim KeyPath As String = "Software\Test"
Registry.CurrentUser.CreateSubKey(KeyPath)
End Sub


Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
CrearValue()
End Sub

Private Sub CrearValue()
Dim KeyPath As String = "Software\Test"
Dim ValueName As String = "TestValue"

Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(KeyPath, True) ' True indica que se abre para escritura
If key IsNot Nothing Then ' Si key es Nothing significa que no se encontró
key.SetValue(ValueName, "Esto es una prueba", RegistryValueKind.String)
Else
If MessageBox.Show(String.Format("No se encontró la clave 'HKCU\{0}'. Desea crearla?", KeyPath), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
CrearKey() ' Creamos la clave y volvemos a intentar crear el valor
CrearValue()
End If
End If
End Sub


Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
EliminarValue()
End Sub

Private Sub EliminarValue()
Dim KeyPath As String = "Software\Test"
Dim ValueName As String = "TestValue"

Dim Key As RegistryKey = Registry.CurrentUser.OpenSubKey(KeyPath, True)

If Key IsNot Nothing Then
If Key.GetValueNames().Contains(ValueName) Then ' Buscamos el nombre del valor en la lista de todos los valores de la clave
Key.DeleteValue(ValueName) ' Borramos el valor
Else
MessageBox.Show(String.Format("No se encontró el valor '{0}'.", ValueName))
End If
Else
MessageBox.Show(String.Format("No se encontró la clave 'HKCU\{0}'.", KeyPath))
End If
End Sub

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
EliminarKey()
End Sub

Private Sub EliminarKey()
Dim KeyPath As String = "Software\Test"

Dim key As RegistryKey = Registry.CurrentUser.OpenSubKey(KeyPath)

If key IsNot Nothing Then
Registry.CurrentUser.DeleteSubKey(KeyPath) ' Borramos la sub clave
Else
MessageBox.Show(String.Format("No se encontró la clave 'HKCU\{0}'.", KeyPath))
End If
End Sub


Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
LeerRegistro()
End Sub

Private Sub LeerRegistro()
Dim KeyPath As String = "Software\Microsoft\Windows\CurrentVersion\Run"
Dim key As RegistryKey = Registry.LocalMachine.OpenSubKey(KeyPath, False) ' Abrimos para sólo lectura

If key IsNot Nothing Then
Dim sb As New System.Text.StringBuilder()

Dim values As String() = key.GetValueNames() ' Obtenemos los nombres de todos los valores en la key
For Each value As String In values
sb.AppendLine(String.Format("{0} > {1} ({2})", value, key.GetValue(value), key.GetValueKind(value).ToString()))
Next

Me.TextBox1.Text = sb.ToString() ' Mostramos el resultado en nuestra TextBox Multilínea
End If
End Sub
End Class


Registro de Windows - Aprendiendo.NET

1 comentario:

  1. Hola, te agradezco mucho por esta explicación.
    Todo está muy bien explicado y entendible.
    Muchas gracias!

    ResponderEliminar