- How to: Create a Registry Key and Set Its Value in Visual Basic
- Procedure
- To create a registry key
- To create a registry key and set a value in it
- Example
- Robust Programming
- .NET Framework Security
- How to create a key in the registry (C# Programming Guide)
- Example
- Compiling the Code
- Robust Programming
- .NET Security
- How to add, modify, or delete registry subkeys and values by using a .reg file
- IN THIS TASK
- Summary
- Как создать ключ реестра в Windows 10?
- Иерархия реестра
- Как создать ключ реестра в Windows 10
- Что делает ключ реестра?
How to: Create a Registry Key and Set Its Value in Visual Basic
The CreateSubKey method of the My.Computer.Registry object can be used to create a registry key.
Procedure
To create a registry key
Use the CreateSubKey method, specifying which hive to place the key under as well as the name of the key. The parameter Subkey is not case-sensitive. This example creates the registry key MyTestKey under HKEY_CURRENT_USER.
To create a registry key and set a value in it
Use the CreateSubkey method, specifying which hive to place the key under as well as the name of the key. This example creates the registry key MyTestKey under HKEY_CURRENT_USER.
Set the value with the SetValue method. This example sets the string value. «MyTestKeyValue» to «This is a test value».
Example
This example creates the registry key MyTestKey under HKEY_CURRENT_USER and then sets the string value MyTestKeyValue to This is a test value .
Robust Programming
Examine the registry structure to find a suitable location for your key. For example, you may want to open the HKEY_CURRENT_USER\Software key of the current user, and create a key with your company’s name. Then add the registry values to your company’s key.
When reading the registry from a Web application, the current user depends on the authentication and impersonation implemented in the Web application.
It is more secure to write data to the user folder (CurrentUser) rather than to the local computer (LocalMachine).
When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a malicious one, may have already created the value and have access to it. When you put data in the registry value, the data is available to the other process. To prevent this, use the GetValue method. It returns Nothing if the key does not already exist.
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by ACLs (Access Control Lists).
The following conditions may cause an exception:
The name of the key is Nothing (ArgumentNullException).
The user does not have permissions to create registry keys (SecurityException).
The key name exceeds the 255-character limit (ArgumentException).
.NET Framework Security
To run this process, your assembly requires a privilege level granted by the RegistryPermission class. If you are running in a partial-trust context, the process might throw an exception due to insufficient privileges. Similarly, the user must have the correct ACLs for creating or writing to settings. For example, a local application that has the code access security permission might not have operating system permission. For more information, see Code Access Security Basics.
How to create a key in the registry (C# Programming Guide)
This example adds the value pair, «Name» and «Isabella», to the current user’s registry, under the key «Names».
Example
Compiling the Code
Copy the code and paste it into the Main method of a console application.
Replace the Names parameter with the name of a key that exists directly under the HKEY_CURRENT_USER node of the registry.
Replace the Name parameter with the name of a value that exists directly under the Names node.
Robust Programming
Examine the registry structure to find a suitable location for your key. For example, you might want to open the Software key of the current user, and create a key with your company’s name. Then add the registry values to your company’s key.
The following conditions might cause an exception:
The name of the key is null.
The user does not have permissions to create registry keys.
The key name exceeds the 255-character limit.
The key is closed.
The registry key is read-only.
.NET Security
It is more secure to write data to the user folder — Microsoft.Win32.Registry.CurrentUser — rather than to the local computer — Microsoft.Win32.Registry.LocalMachine .
When you create a registry value, you need to decide what to do if that value already exists. Another process, perhaps a malicious one, may have already created the value and have access to it. When you put data in the registry value, the data is available to the other process. To prevent this, use the. Overload:Microsoft.Win32.RegistryKey.GetValue method. It returns null if the key does not already exist.
It is not secure to store secrets, such as passwords, in the registry as plain text, even if the registry key is protected by access control lists (ACL).
How to add, modify, or delete registry subkeys and values by using a .reg file
This article is intended for advanced users, administrators, and IT Professionals.
Importing Registration Entries (.reg) files is a feature of Regedit.exe and is not supported by Regedt32.exe. You can use Regedit.exe to make some changes to the registry on a Windows NT 4.0-based or Windows 2000-based computer, but some changes require Regedt32.exe. For example, you cannot add or change REG_EXPAND_SZ or REG_MULTI_SZ values with Regedit.exe on a Windows NT 4.0-based or Windows 2000-based computer. Regedt32.exe is the primary Registry Editor for Windows NT 4.0 and Windows 2000. If you must use Regedt32.exe, you cannot use Registration Entries (.reg) files to modify the registry. For more information about the differences between Regedit.exe and Regedt32.exe, click the following article number to view the article in the Microsoft Knowledge Base:
141377 Differences between Regedit.exe and Regedt32.exe
IN THIS TASK
Summary
Important This section, method, or task contains steps that tell you how to modify the registry. However, serious problems might occur if you modify the registry incorrectly. Therefore, make sure that you follow these steps carefully. For added protection, back up the registry before you modify it. Then, you can restore the registry if a problem occurs. For more information about how to back up and restore the registry, click the following article number to view the article in the Microsoft Knowledge Base:
322756 How to back up and restore the registry in Windows This step-by-step article describes how to add, modify, or delete registry subkeys and values by using a Registration Entries (.reg) file. Regedit.exe uses .reg files to import and export registry subkeys and values. You can use these .reg files to remotely distribute registry changes to several Windows-based computers. When you run a .reg file, the file contents merge into the local registry. Therefore, you must distribute .reg files with caution.
A .reg file has the following syntax:
RegistryEditorVersion
Blank line
[ RegistryPath1]
» DataItemName1«=» DataType1: DataValue1»
DataItemName2«=» DataType2: DataValue2»
Blank line
[ RegistryPath2]
» DataItemName3«=» DataType3: DataValue3«
RegistryEditorVersion is either «Windows Registry Editor Version 5.00» for Windows 2000, Windows XP, and Windows Server 2003, or «REGEDIT4» for Windows 98 and Windows NT 4.0. The «REGEDIT4» header also works on Windows 2000-based, Windows XP-based, and Windows Server 2003-based computers.
Blank line is a blank line. This identifies the start of a new registry path. Each key or subkey is a new registry path. If you have several keys in your .reg file, blank lines can help you to examine and to troubleshoot the contents.
RegistryPathx is the path of the subkey that holds the first value you are importing. Enclose the path in square brackets, and separate each level of the hierarchy by a backslash. For example:
[ HKEY_LOCAL_ MACHINE\SOFTWARE\Policies\Microsoft\Windows\System] A .reg file can contain several registry paths. If the bottom of the hierarchy in the path statement does not exist in the registry, a new subkey is created. The contents of the registry files are sent to the registry in the order you enter them. Therefore, if you want to create a new subkey with another subkey below it, you must enter the lines in the correct order.
DataItemNamex is the name of the data item that you want to import. If a data item in your file does not exist in the registry, the .reg file adds it (with the value of the data item). If a data item does exist, the value in your .reg file overwrites the existing value. Quotation marks enclose the name of the data item. An equal sign (=) immediately follows the name of the data item.
Как создать ключ реестра в Windows 10?
Реестр Windows — это набор настроек, которые могут использовать Windows и приложения. Это каталог, в котором хранятся настройки и параметры операционной системы для Microsoft Windows. Он содержит информацию и настройки для всего аппаратного обеспечения, программного обеспечения операционной системы, большинства программ, не относящихся к операционной системе, пользователей, предпочтений ПК и т.д. Реестр состоит из следующих 5 корневых ключей. Корневые ключи содержат SubKeys. Подключи могут также содержать свои собственные подключи и содержать как минимум одно значение, называемое его значением по умолчанию. Ключ со всеми его подразделами и значениями называется Hive. Каждый ключ имеет один из типов данных — типы данных: REG_SZ, REG_BINARY, REG_DWORD, REG_QWORD, REG_MULTI_SZ или REG_EXPAND_SZ.
В этом посте мы покажем вам, как создать раздел реестра в Windows 10.
Прежде чем начать, всегда рекомендуется создать резервную копию реестра или создать точку восстановления системы .
Реестр Windows сложен по архитектуре и построен так, что обычные потребители не поймут. Также желательно, чтобы вы знали основы и не изменяли их, если не знаете, что делаете.
Иерархия реестра
Для редактирования реестра мы используем встроенный редактор реестра или regedit. Он отображает древовидную структуру навигации. Самым верхним является ваш компьютер, за которым следует список папок и подпапок. Эти папки называются KEYS, и в компьютере есть пять фиксированных наборов папок.
- HKEY_CLASSES_ROOT: содержит информацию об ассоциации расширений файлов, которая помогает компьютеру понять, что делать с задачей при запросе.
- HKEY_CURRENT_USER: содержит информацию о конфигурации для Windows и программное обеспечение для текущего пользователя.
- HKEY_LOCAL_MACHINE: хранит конфигурацию для программного обеспечения, установленного на компьютере, а также для ОС Windows
- HKEY_USERS: здесь вы можете найти пользовательскую конфигурацию для всех пользователей на этом компьютере.
- HKEY_CURRENT_CONFIG: это указатель на HKEY_LOCAL_MACHINE
Это мастер-ключи, поскольку вы не можете создать НОВЫЙ КЛЮЧ в разделе «Компьютер», но вы можете сгенерировать новые ключи под любым из этих мастер-ключей.
Как создать ключ реестра в Windows 10
1] Использование редактора реестра
Создать ключ реестра легко. Щелкните правой кнопкой мыши любую папку или пробел и выберите «Создать». Вы можете создать ключ, строковое значение, двоичное значение, значение DWORD (32-разрядное), значение QWORD (64-разрядное), многостроковое значение или расширяемое строковое значение. Этот метод полезен, когда вы планируете внести незначительные изменения, чтобы исправить проблему на вашем компьютере. Это может быть связано с приложением или на уровне ОС.
- Чтобы отредактировать существующее значение, дважды щелкните его, чтобы запустить редактор.
- Чтобы удалить ключ, щелкните его правой кнопкой мыши и выберите «Удалить».
- У вас также есть возможность переименовать, экспортировать, копировать и установить разрешения.
2] Используйте Блокнот для создания файлов REG
Щелкните правой кнопкой мыши по любому из существующих ключей и экспортируйте его. Откройте этот файл в блокноте, и он поможет вам понять, как вы можете редактировать ключ и его значения. Это полезно, когда вы хотите выполнить массовое редактирование с резервным копированием на месте.
Обратите внимание на объявление версии, за которым следует пустая строка, затем путь, за которым следует остаток в кавычках, и снова пустая строка. После завершения редактирования вы можете щелкнуть правой кнопкой мыши и выбрать объединить файл в куст реестра.
3] Сторонние инструменты
Если вы нашли редактор реестра по умолчанию сложным, вы можете использовать такие инструменты, как RegCool, Registry Manager Lite. Они предлагают такие функции, как Отмена, Повторить, управление разрешениями, окно с вкладками, импорт, экспорт, избранное и так далее.
3] Напишите свою программу
Если вы разработчик приложения, вам следует использовать программирование для управления настройками приложения в реестре. Вот пример, и он будет варьироваться в зависимости от языка, который вы используете для разработки приложения.
Теперь, когда вы знаете, как это сделать, мы также рекомендуем вам прочитать, что означает каждый из них. Это важно и поможет вам убедиться, что внесенные вами изменения верны.
Что делает ключ реестра?
Если вы представляете «Ключ» как папку, остальные представляют собой различные типы типов файлов, в которых хранятся различные типы значений. Таким образом, если вы создаете приложение, вы можете иметь основную папку, а затем подпапки, чтобы отделить один набор от другого. Вот немного о каждом из них:
DWORD & QWORD: Double Word может хранить 32-битные единицы данных, в то время как QWORD может хранить 64-битные данные.
Строковое значение (REG_SZ): может хранить строку в формате Unicode или ANSI и в конце содержит ноль.
Multi-String value: Если вы хотите сохранить несколько чисел String Value, вы можете использовать это. Тем не менее, обязательно завершите его пустой строкой (\0). Вот простой пример:
Обратите внимание, что ‘\0’ в конце обозначает конец первой строки, а последний ‘\0’ обозначает конец мультистроки.
Расширяемое строковое значение: это можно использовать для переменных среды с использованием строки Unicode или ANSI. Преимущество здесь в том, что вы можете расширить его в отличие от значений String и Multi-String.
Двоичное значение: самое простое, оно содержит 0 и 1.