Windows registry key class

Registry Класс

Определение

Предоставляет объекты RegistryKey, представляющие корневые разделы в реестре Windows, и методы static для доступа к парам «раздел-значение». Provides RegistryKey objects that represent the root keys in the Windows registry, and static methods to access key/value pairs.

Примеры

Этот раздел содержит два примера кода. This section contains two code examples. В первом примере показаны корневые ключи, а во втором примере демонстрируются static GetValue SetValue методы и. The first example demonstrates root keys, and the second example demonstrates the static GetValue and SetValue methods.

Пример 1 Example 1

В следующем примере кода показано, как получить подразделы ключа HKEY_USERS и распечатать их имена на экране. The following code example demonstrates how to retrieve the subkeys of the HKEY_USERS key, and print their names to the screen. Используйте OpenSubKey метод, чтобы создать экземпляр определенного подраздела, представляющего интерес. Use the OpenSubKey method to create an instance of the particular subkey of interest. Затем можно использовать другие операции в RegistryKey для управления этим ключом. You can then use other operations in RegistryKey to manipulate that key.

Пример 2 Example 2

Следующий пример кода сохраняет значения нескольких типов данных в примере ключа, создавая ключ, как это делает, а затем извлекает и отображает значения. The following code example stores values of several data types in an example key, creating the key as it does so, and then retrieves and displays the values. В примере демонстрируется хранение и извлечение пары «имя-значение» по умолчанию (без имени) и использования, defaultValue Если пара «имя-значение» не существует. The example demonstrates storing and retrieving the default (nameless) name/value pair, and the use of defaultValue when a name/value pair does not exist.

Комментарии

Этот класс предоставляет набор стандартных корневых ключей, которые находятся в реестре на компьютерах под Windows. This class provides the set of standard root keys found in the registry on machines running Windows. Реестр — это средство хранения сведений о приложениях, пользователях и системных параметрах по умолчанию. The registry is a storage facility for information about applications, users, and default system settings. Например, приложения могут использовать реестр для хранения сведений, которые необходимо сохранить после закрытия приложения, и получить доступ к той же информации при повторной загрузке приложения. For example, applications can use the registry for storing information that needs to be preserved after the application is closed, and access that same information when the application is reloaded. Например, можно сохранять настройки цвета, расположения экрана или размер окна. For instance, you can store color preferences, screen locations, or the size of the window. Эти данные можно контролировать для каждого пользователя, сохраняя их в другом месте реестра. You can control this data for each user by storing the information in a different location in the registry.

Базовые или корневые RegistryKey экземпляры, предоставляемые Registry классом, обделяют базовый механизм хранения для подразделов и значений в реестре. The base, or root RegistryKey instances that are exposed by the Registry class delineate the basic storage mechanism for subkeys and values in the registry. Все ключи доступны только для чтения, так как реестр зависит от их существования. All keys are read-only because the registry depends on their existence. Ключи, предоставляемые Registry : The keys exposed by Registry are:

CurrentUser Хранит сведения о предпочтениях пользователя. CurrentUser Stores information about user preferences.

LocalMachine Хранит сведения о конфигурации для локального компьютера. LocalMachine Stores configuration information for the local machine.

ClassesRoot Хранит сведения о типах (и классах) и их свойствах. ClassesRoot Stores information about types (and classes) and their properties.

Users Хранит сведения о пользовательской конфигурации по умолчанию. Users Stores information about the default user configuration.

PerformanceData Хранит сведения о производительности компонентов программного обеспечения. PerformanceData Stores performance information for software components.

CurrentConfig Хранит сведения об оборудовании, не относящемся к пользователю. CurrentConfig Stores non-user-specific hardware information.

Читайте также:  Lumia 640 как прошить windows 10

DynData Хранит динамические данные. DynData Stores dynamic data.

Определив корневой ключ, в котором необходимо хранить или извлекать сведения из реестра, можно использовать RegistryKey класс для добавления или удаления подразделов и управления значениями для данного ключа. Once you have identified the root key under which you want to store/retrieve information from the registry, you can use the RegistryKey class to add or remove subkeys, and manipulate the values for a given key.

Аппаратные устройства могут автоматически размещать данные в реестре с помощью интерфейса самонастраивающийся. Hardware devices can place information in the registry automatically using the Plug and Play interface. Программное обеспечение для установки драйверов устройств может размещать сведения в реестре, записывая их в стандартные API. Software for installing device drivers can place information in the registry by writing to standard APIs.

Статические методы для получения и установки значений Static Methods for Getting and Setting Values

RegistryКласс также содержит static GetValue методы и SetValue для установки и получения значений из разделов реестра. The Registry class also contains static GetValue and SetValue methods for setting and retrieving values from registry keys. Эти методы открывают и закрывают разделы реестра при каждом использовании, поэтому они не выполняют, а также аналогичные методы в RegistryKey классе при доступе к большому количеству значений. These methods open and close registry keys each time they are used, so they do not perform as well as analogous methods in the RegistryKey class, when you access a large number of values.

RegistryKeyКласс также предоставляет методы, позволяющие задать параметры безопасности управления доступом Windows для разделов реестра, чтобы проверить тип данных значения перед его получением и удалить ключи. The RegistryKey class also provides methods that allow you to set Windows access control security for registry keys, to test the data type of a value before retrieving it, and to delete keys.

Определяет типы (или классы) документов и свойства, связанные с этими типами. Defines the types (or classes) of documents and the properties associated with those types. Это поле считывает базовый раздел реестра Windows HKEY_CLASSES_ROOT. This field reads the Windows registry base key HKEY_CLASSES_ROOT.

Содержит сведения о конфигурации, относящиеся к оборудованию, не связанному с конкретным пользователем. Contains configuration information pertaining to the hardware that is not specific to the user. Это поле считывает базовый раздел реестра Windows HKEY_CURRENT_CONFIG. This field reads the Windows registry base key HKEY_CURRENT_CONFIG.

Содержит сведения о текущих пользовательских параметрах. Contains information about the current user preferences. Это поле считывает базовый раздел реестра Windows HKEY_CURRENT_USER. This field reads the Windows registry base key HKEY_CURRENT_USER.

Содержит динамические данные реестра. Contains dynamic registry data. Это поле считывает базовый раздел реестра Windows HKEY_DYN_DATA. This field reads the Windows registry base key HKEY_DYN_DATA.

Содержит данные о конфигурации для локального компьютера. Contains the configuration data for the local machine. Это поле считывает базовый раздел реестра Windows HKEY_LOCAL_MACHINE. This field reads the Windows registry base key HKEY_LOCAL_MACHINE.

Содержит сведения о производительности для компонентов программного обеспечения. Contains performance information for software components. Это поле считывает базовый раздел реестра Windows HKEY_PERFORMANCE_DATA. This field reads the Windows registry base key HKEY_PERFORMANCE_DATA.

Содержит сведения о стандартной пользовательской конфигурации. Contains information about the default user configuration. Это поле считывает базовый раздел реестра Windows HKEY_USERS. This field reads the Windows registry base key HKEY_USERS.

Методы

Извлекает значение, связанное с указанным именем, в указанном разделе реестра. Retrieves the value associated with the specified name, in the specified registry key. Если имя не найдено в указанном разделе, возвращает предоставленное значение по умолчанию или значение null , если указанный раздел не существует. If the name is not found in the specified key, returns a default value that you provide, or null if the specified key does not exist.

Задает указанное значение пары «имя-значение» для указанного раздела реестра. Sets the specified name/value pair on the specified registry key. Если указанный раздел не существует, он будет создан. If the specified key does not exist, it is created.

Читайте также:  Не грузит параметры windows 10

Задает пару «имя-значение» для указанного раздела реестра, используя указанный тип данных реестра. Sets the name/value pair on the specified registry key, using the specified registry data type. Если указанный раздел не существует, он будет создан. If the specified key does not exist, it is created.

Registry Key Class

Definition

Represents a key-level node in the Windows registry. This class is a registry encapsulation.

Examples

The following code example shows how to create a subkey under HKEY_CURRENT_USER, manipulate its contents, and then delete the subkey.

Remarks

To get an instance of RegistryKey, use one of the static members of the Registry class.

The registry acts as a central repository of information for the operating system and the applications on a computer. The registry is organized in a hierarchical format, based on a logical ordering of the elements stored within it (please see Registry for the base-level items in this hierarchy). When storing information in the registry, select the appropriate location based on the type of information being stored. Be sure to avoid destroying information created by other applications, because this can cause those applications to exhibit unexpected behavior, and can also have an adverse effect upon your own application.

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try / catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the «Using an Object that Implements IDisposable» section in the IDisposable interface topic.

Registry keys are the base unit of organization in the registry, and can be compared to folders in File Explorer. A particular key can have subkeys, just as a folder can have subfolders. Each key can be deleted, as long as the user has the appropriate permissions to do so, and the key is not a base key or at the level directly under the base keys. Each key can also have multiple values associated with it (a value can be compared to a file), which are used to store the information — for example, information about an application installed on the computer. Each value holds one particular piece of information, which can be retrieved or updated when required. For instance, you can create a RegistryKey for your company, under the key HKEY_LOCAL_MACHINE\Software, and then a subkey for each application that your company creates. Each subkey holds the information specific to that application, such as color settings, screen location and size, or recognized file extensions.

Note that information stored in the registry is available to other applications and users, and therefore should not be used to store security data or critical application information.

Do not expose RegistryKey objects in such a way that a malicious program could create thousands of meaningless subkeys or key/value pairs. For example, do not allow callers to enter arbitrary keys or values.

Starting in the .NET Framework 4, the length of a registry key is no longer limited to 255 characters.

Properties

Gets a SafeRegistryHandle object that represents the registry key that the current RegistryKey object encapsulates.

Retrieves the name of the key.

Retrieves the count of subkeys of the current key.

Retrieves the count of values in the key.

Gets the view that was used to create the registry key.

Methods

Closes the key and flushes it to disk if its contents have been modified.

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject) CreateSubKey(String)

Creates a new subkey or opens an existing subkey for write access.

Creates a new subkey or opens an existing subkey with the specified access. Available starting with .NET Framework 4.6.

Creates a new subkey or opens an existing subkey with the specified access. Available starting with .NET Framework 4.6.

Читайте также:  Kali linux как зайти под рутом

Creates a new subkey or opens an existing subkey for write access, using the specified permission check option.

Creates a subkey or opens a subkey for write access, using the specified permission check and registry options.

Creates a subkey or opens a subkey for write access, using the specified permission check option, registry option, and registry security.

Creates a new subkey or opens an existing subkey for write access, using the specified permission check option and registry security.

Deletes the specified subkey.

Deletes the specified subkey, and specifies whether an exception is raised if the subkey is not found.

Deletes a subkey and any child subkeys recursively.

Deletes the specified subkey and any child subkeys recursively, and specifies whether an exception is raised if the subkey is not found.

Deletes the specified value from this key.

Deletes the specified value from this key, and specifies whether an exception is raised if the value is not found.

Releases all resources used by the current instance of the RegistryKey class.

Determines whether the specified object is equal to the current object.

(Inherited from Object) Finalize()

Closes the key and flushes it to disk if the contents have been modified.

Writes all the attributes of the specified open registry key into the registry.

Creates a registry key from a specified handle.

Creates a registry key from a specified handle and registry view setting.

Returns the access control security for the current registry key.

Returns the specified sections of the access control security for the current registry key.

Serves as the default hash function.

(Inherited from Object) GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject) GetSubKeyNames()

Retrieves an array of strings that contains all the subkey names.

Gets the Type of the current instance.

(Inherited from Object) GetValue(String)

Retrieves the value associated with the specified name. Returns null if the name/value pair does not exist in the registry.

Retrieves the value associated with the specified name. If the name is not found, returns the default value that you provide.

Retrieves the value associated with the specified name and retrieval options. If the name is not found, returns the default value that you provide.

Retrieves the registry data type of the value associated with the specified name.

Retrieves an array of strings that contains all the value names associated with this key.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject) OpenBaseKey(RegistryHive, RegistryView)

Opens a new RegistryKey that represents the requested key on the local machine with the specified view.

Opens a new RegistryKey that represents the requested key on a remote machine.

Opens a new registry key that represents the requested key on a remote machine with the specified view.

Retrieves a subkey as read-only.

Retrieves a specified subkey, and specifies whether write access is to be applied to the key.

Retrieves the specified subkey for read or read/write access.

Retrieves the specified subkey for read or read/write access, requesting the specified access rights.

Retrieves a subkey with the specified name and access rights. Available starting with .NET Framework 4.6.

Applies Windows access control security to an existing registry key.

Sets the specified name/value pair.

Sets the value of a name/value pair in the registry key, using the specified registry data type.

Retrieves a string representation of this key.

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

This API supports the product infrastructure and is not intended to be used directly from your code.

Performs a Close() on the current key.

Extension Methods

Returns the security information of a registry key.

Returns the security information of a registry key.

Changes the security attributes of an existing registry key.

Оцените статью