Este é um conteúdo traduzido por máquina.
Biblioteca de classes do .NET Framework
Classe RegistryKey

Representa um nó de nível de chave no Registro do Windows. Essa classe é um encapsulamento de registro.

Namespace:  Microsoft.Win32
Assembly:  mscorlib (em mscorlib. dll)
Sintaxe

Visual Basic (Declaração)
<ComVisibleAttribute(True)> _
Public NotInheritable Class RegistryKey _
    Inherits MarshalByRefObject _
    Implements IDisposable
Visual Basic (Uso)
Dim instance As RegistryKey
C#
[ComVisibleAttribute(true)]
public sealed class RegistryKey : MarshalByRefObject, 
    IDisposable
Visual C++
[ComVisibleAttribute(true)]
public ref class RegistryKey sealed : public MarshalByRefObject, 
    IDisposable
JScript
public final class RegistryKey extends MarshalByRefObject implements IDisposable
Comentários

Para obter uma instância de RegistryKey, use o um dos membros estáticos da classe Registry.

O registro atua como um repositório central de informações para o sistema operacional e os aplicativos em um computador. O registro é organizado em um Formatarar hierárquico, com base em uma ordem lógica dos elementos armazenados dentro de ele (consulte Registry para os itens nível base dessa hierarquia). Ao armazenar informações no registro, Selecionar o local apropriado dependendo do tipo de informações sejam armazenadas. Certifique-se de evitar destruir informações Criado por outros aplicativos, porque isso pode causar esses aplicativos para apresentar um comportamento inesperado e também pode ter um efeito adverso no seu próprio aplicativo.

Chaves do Registro são a unidade base da organização no registro e podem ser comparadas para pastas no Windows Explorer. Uma chave particular pode ter subchaves, assim como uma pasta pode ter subpastas. Cada chave pode ser excluído, contanto que o usuário tem as permissões apropriadas para fazer isso, e a chave não é uma chave de base ou no nível diretamente sob as chaves base. Cada chave também pode ter Múltiplo valores associados a ele (um valor pode ser comparado a um arquivo), que são usados para armazenar as informações — por exemplo, informações sobre um aplicativo instalado no computador. Cada valor contém um dado específico informações, que podem ser recuperados ou atualizados quando necessário. Por exemplo, você pode criar um RegistryKey para a sua empresa, sob a chave HKEY_LOCAL_MACHINE\Software e em seguida, uma subchave para cada aplicativo que sua empresa cria. Cada subchave contém as informações específicas desse aplicativo, como configurações de cor, localização de tela e o tamanho, ou as extensões de arquivo reconhecidas.

Anotação que informações armazenadas no Registro está disponíveis para outros aplicativos e usuários e, portanto, não devem ser usadas para armazenar dados de segurança ou informações de aplicativo crítico.

Observação de cautelaCuidado:

Não exponha RegistryKey objetos de tal forma que um programa mal-intencionado pode criar milhares de subchaves sem sentido ou pares chave/valor. Por exemplo, não permitir chamadores para Enter arbitrárias chaves ou valores.

Anotação de plataforma Windows Mobile para Pocket PC, Windows Mobile para Smartphone, O Windows CE:

Em aplicativos .NET Compact Framework, antes de excluir uma subchave qualquer Abrir instâncias da subchave e suas subchaves filho devem ser explicitamente fechadas. A profundidade máxima de subchaves, conforme determinado pelo Windows CE, é 15.

Exemplos

O exemplo de código seguinte mostra como criar uma subchave em HKEY_CURRENT_USER, manipular seu conteúdo e, em seguida, Excluir a subchave.

Visual Basic
Imports Microsoft.VisualBasic
Imports System
Imports System.Security.Permissions
Imports Microsoft.Win32

<Assembly: RegistryPermissionAttribute( _
    SecurityAction.RequestMinimum, ViewAndModify := "HKEY_CURRENT_USER")>

Public Class RegKey
    Shared Sub Main()

        ' Create a subkey named Test9999 under HKEY_CURRENT_USER.
        Dim test9999 As RegistryKey = _
            Registry.CurrentUser.CreateSubKey("Test9999")

        ' Create two subkeys under HKEY_CURRENT_USER\Test9999.
        test9999.CreateSubKey("TestName").Close()
        Dim testSettings As RegistryKey = _
            test9999.CreateSubKey("TestSettings")

        ' Create data for the TestSettings subkey.
        testSettings.SetValue("Language", "French")
        testSettings.SetValue("Level", "Intermediate")
        testSettings.SetValue("ID", 123)
        testSettings.Close()

        ' Print the information from the Test9999 subkey.
        Console.WriteLine("There are {0} subkeys under Test9999.", _
            test9999.SubKeyCount.ToString())
        For Each subKeyName As String In test9999.GetSubKeyNames()
            Dim tempKey As RegistryKey = _
                test9999.OpenSubKey(subKeyName)
            Console.WriteLine(vbCrLf & "There are {0} values for " & _
                "{1}.", tempKey.ValueCount.ToString(), tempKey.Name)
            For Each valueName As String In tempKey.GetValueNames()
                Console.WriteLine("{0,-8}: {1}", valueName, _
                    tempKey.GetValue(valueName).ToString())
            Next
        Next

        ' Delete the ID value.
        testSettings = test9999.OpenSubKey("TestSettings", True)
        testSettings.DeleteValue("id")

        ' Verify the deletion.
        Console.WriteLine(CType(testSettings.GetValue( _
            "id", "ID not found."), String))
        testSettings.Close()

        ' Delete or close the new subkey.
        Console.Write(vbCrLf & "Delete newly created " & _
            "registry key? (Y/N) ")
        If Char.ToUpper(Convert.ToChar(Console.Read())) = "Y"C Then
            Registry.CurrentUser.DeleteSubKeyTree("Test9999")
            Console.WriteLine(vbCrLf & "Registry key {0} deleted.", _
                test9999.Name)
        Else
            Console.WriteLine(vbCrLf & "Registry key {0} closed.", _
                test9999.ToString())
            test9999.Close()
        End If

    End Sub
End Class
C#
using System;
using System.Security.Permissions;
using Microsoft.Win32;

[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum,
    ViewAndModify = "HKEY_CURRENT_USER")]

class RegKey
{
    static void Main()
    {
        // Create a subkey named Test9999 under HKEY_CURRENT_USER.
        RegistryKey test9999 = 
            Registry.CurrentUser.CreateSubKey("Test9999");
        // Create two subkeys under HKEY_CURRENT_USER\Test9999. The
        // keys are disposed when execution exits the using statement.
        using(RegistryKey 
            testName = test9999.CreateSubKey("TestName"),
            testSettings = test9999.CreateSubKey("TestSettings"))
        {
            // Create data for the TestSettings subkey.
            testSettings.SetValue("Language", "French");
            testSettings.SetValue("Level", "Intermediate");
            testSettings.SetValue("ID", 123);
        }

        // Print the information from the Test9999 subkey.
        Console.WriteLine("There are {0} subkeys under {1}.", 
            test9999.SubKeyCount.ToString(), test9999.Name);
        foreach(string subKeyName in test9999.GetSubKeyNames())
        {
            using(RegistryKey 
                tempKey = test9999.OpenSubKey(subKeyName))
            {
                Console.WriteLine("\nThere are {0} values for {1}.", 
                    tempKey.ValueCount.ToString(), tempKey.Name);
                foreach(string valueName in tempKey.GetValueNames())
                {
                    Console.WriteLine("{0,-8}: {1}", valueName, 
                        tempKey.GetValue(valueName).ToString());
                }
            }
        }

        using(RegistryKey 
            testSettings = test9999.OpenSubKey("TestSettings", true))
        {
            // Delete the ID value.
            testSettings.DeleteValue("id");

            // Verify the deletion.
            Console.WriteLine((string)testSettings.GetValue(
                "id", "ID not found."));
        }

        // Delete or close the new subkey.
        Console.Write("\nDelete newly created registry key? (Y/N) ");
        if(Char.ToUpper(Convert.ToChar(Console.Read())) == 'Y')
        {
            Registry.CurrentUser.DeleteSubKeyTree("Test9999");
            Console.WriteLine("\nRegistry key {0} deleted.", 
                test9999.Name);
        }
        else
        {
            Console.WriteLine("\nRegistry key {0} closed.", 
                test9999.ToString());
            test9999.Close();
        }
    }
}
Visual C++
using namespace System;
using namespace System::Security::Permissions;
using namespace Microsoft::Win32;

[assembly:RegistryPermissionAttribute(SecurityAction::RequestMinimum,
ViewAndModify="HKEY_CURRENT_USER")];
int main()
{
   // Create a subkey named Test9999 under HKEY_CURRENT_USER.
   RegistryKey ^ test9999 = Registry::CurrentUser->CreateSubKey( "Test9999" );

   // Create two subkeys under HKEY_CURRENT_USER\Test9999.
   test9999->CreateSubKey( "TestName" )->Close();
   RegistryKey ^ testSettings = test9999->CreateSubKey( "TestSettings" );

   // Create data for the TestSettings subkey.
   testSettings->SetValue( "Language", "French" );
   testSettings->SetValue( "Level", "Intermediate" );
   testSettings->SetValue( "ID", 123 );
   testSettings->Close();

   // Print the information from the Test9999 subkey.
   Console::WriteLine( "There are {0} subkeys under Test9999.", test9999->SubKeyCount.ToString() );
   array<String^>^subKeyNames = test9999->GetSubKeyNames();
   for ( int i = 0; i < subKeyNames->Length; i++ )
   {
      RegistryKey ^ tempKey = test9999->OpenSubKey( subKeyNames[ i ] );
      Console::WriteLine( "\nThere are {0} values for {1}.", tempKey->ValueCount.ToString(), tempKey->Name );
      array<String^>^valueNames = tempKey->GetValueNames();
      for ( int j = 0; j < valueNames->Length; j++ )
      {
         Console::WriteLine( "{0,-8}: {1}", valueNames[ j ], tempKey->GetValue( valueNames[ j ] )->ToString() );

      }
   }

   // Delete the ID value.
   testSettings = test9999->OpenSubKey( "TestSettings", true );
   testSettings->DeleteValue( "id" );

   // Verify the deletion.
   Console::WriteLine( dynamic_cast<String^>(testSettings->GetValue(  "id", "ID not found." )) );
   testSettings->Close();

   // Delete or close the new subkey.
   Console::Write( "\nDelete newly created registry key? (Y/N) " );
   if ( Char::ToUpper( Convert::ToChar( Console::Read() ) ) == 'Y' )
   {
      Registry::CurrentUser->DeleteSubKeyTree( "Test9999" );
      Console::WriteLine( "\nRegistry key {0} deleted.", test9999->Name );
   }
   else
   {
      Console::WriteLine( "\nRegistry key {0} closed.", test9999->ToString() );
      test9999->Close();
   }
}
Hierarquia de herança

System..::.Object
  System..::.MarshalByRefObject
    Microsoft.Win32..::.RegistryKey
Segurança de Segmentos

Quaisquer membros público estático (compartilhado no Visual Basic) deste tipo são processos seguros. Quaisquer membros de instância não são garantidos como processos seguros.
Plataformas

Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, O Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC

O .NET Framework e .NET Compact Framework não suporte para todas as versões de cada plataforma. Para obter uma lista das versões com suporte, consulte Requisitos de sistema do .NET framework.
Informações de versão

.NET Framework

Compatível com: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatível com: 3.5, 2.0
Consulte também

Referência

Marcas :


Page view tracker