Windows Registry is a hierarchical database that stores configuration settings and options on Microsoft Windows operating systems. It contains settings for low-level operating system components as well as the applications running on the platform: the kernel, device drivers, services, SAM, user interface and third party applications all make use of the Registry. The registry also provides a means to access counters for profiling system performance.
When first introduced with Windows 3.1, the Windows registry’s primary purpose was to store configuration information for COM-based components. With the introduction of Windows 95 and Windows NT, its use was extended to tidy up the profusion of per-program INI files that had previously been used to store configuration settings for Windows programs.[1]
Rationale[]
.INI files stored each program’s user settings in a separate file. By contrast, the Windows registry stores all application settings in one central repository and in a standardized form. This offers several advantages over INI files.[2] Since accessing the registry does not require parsing, it may be read from or written to more quickly than an INI file. As well, strongly-typed data can be stored in the registry, as opposed to the text information stored in INI files. Because user-based registry settings are loaded from a user-specific path rather than from a read-only system location, the registry allows multiple users to share the same machine, and also allows programs to work for a least-privilege user. Backup and restoration is also simplified as the registry can be accessed over a network connection for remote management/support, including from scripts, using the standard set of APIs, as long as the Remote Registry service is running and firewall rules permit this.
The registry has features that improve system integrity, as the registry is constructed as a database and offers database-like features such as atomic updates. If two processes attempt to update the same registry value at the same time, one process’s change will precede the other’s and the overall consistency of the data will be maintained. Where changes are made to INI files, such race conditions can result in inconsistent data which doesn’t match either attempted update. Windows Vista and Windows 7 provide transactional updates to the registry, extending the atomicity guarantees across multiple key and/or value changes, with traditional commit-abort semantics. (Note however that NTFS provides such support for the file system as well, so the same guarantees could, in theory, be obtained with traditional configuration files.)
Structure[]
Keys and values[]
The registry contains two basic elements: keys and values.
Registry Keys are similar to folders — in addition to values, each key can contain subkeys, which may contain further subkeys, and so on. Keys are referenced with a syntax similar to Windows’ path names, using backslashes to indicate levels of hierarchy. E.g. HKEY_LOCAL_MACHINE\Software\Microsoft\Windows refers to the subkey «Windows» of the subkey «Microsoft» of the subkey «Software» of the HKEY_LOCAL_MACHINE key.
There are six Root Keys:
- HKEY_CLASSES_ROOT
- HKEY_CURRENT_USER
- HKEY_LOCAL_MACHINE
- HKEY_USERS
- HKEY_CURRENT_CONFIG
- HKEY_DYN_DATA
Registry Values are name/data pairs stored within keys. Values are referenced separately from keys. Value names can contain backslashes but doing so makes them difficult to distinguish from their key paths. The Windows API functions that query and manipulate registry values take value names separately from the key path and/or handle that identifies the parent key. The terminology is somewhat misleading, as the values are similar to an associative array, where standard terminology would refer to the name part of the value as a «key». The terms are a holdout from the 16-bit registry in Windows 3, in which keys could not contain arbitrary name/data pairs, but rather contained only one unnamed value (which had to be a string). In this sense, the entire registry was like an associative array where the keys (in both the registry sense and dictionary sense) formed a hierarchy, and the values were all strings. When the 32-bit registry was created, so was the additional capability of creating multiple named values per key, and the meanings of the names were somewhat distorted.[3]
There are a number of different types of values:
List of Registry Value Types | ||
---|---|---|
0 | REG_NONE | No type |
1 | REG_SZ | A string value |
2 | REG_EXPAND_SZ | An «expandable» string value that can contain environment variables |
3 | REG_BINARY | Binary data (any arbitrary data) |
4 | REG_DWORD / REG_DWORD_LITTLE_ENDIAN | A DWORD value, a 32-bit unsigned integer (numbers between 0 and 4,294,967,295 [232 – 1]) (little-endian) |
5 | REG_DWORD_BIG_ENDIAN | A DWORD value, a 32-bit unsigned integer (numbers between 0 and 4,294,967,295 [232 – 1]) (big-endian) |
6 | REG_LINK | symbolic link (UNICODE) |
7 | REG_MULTI_SZ | A multi-string value, which is an array of unique strings |
8 | REG_RESOURCE_LIST | Resource list |
9 | REG_FULL_RESOURCE_DESCRIPTOR | Resource descriptor |
10 | REG_RESOURCE_REQUIREMENTS_LIST | Resource Requirements List |
11 | REG_QWORD / REG_QWORD_LITTLE_ENDIAN | A QWORD value, a 64-bit integer (either big- or little-endian, or unspecified) (Introduced in Windows 2000) |
Hives[]
The Registry is split into a number of logical sections, or «hives»[4] (the reason the word hive was used is an in-joke).[5] Hives are generally named by their Windows API definitions, which all begin «HKEY». They are abbreviated to a three- or four-letter short name starting with «HK» (e.g. HKCU and HKLM).
The HKEY_LOCAL_MACHINE (local machine-specific configuration data) and HKEY_CURRENT_USER (user-specific configuration data) nodes have a similar structure to each other; user applications typically look up their settings by first checking for them in «HKEY_CURRENT_USER\Software\Vendor’s name\Application’s name\Version\Setting name», and if the setting is not found, look instead in the same location under the HKEY_LOCAL_MACHINE key[citation needed]. However, the converse may apply for administrator-enforced policy settings where HKLM may take precedence over HKCU. The Windows Logo Program has specific requirements for where different types of user data may be stored, and that the concept of least privilege be followed so that administrator-level access is not required to use an application.[Note 1][6]
HKEY_CLASSES_ROOT (HKCR)[]
Abbreviated HKCR, HKEY_CLASSES_ROOT stores information about registered applications, such as file associations and OLE Object Class IDs, tying them to the applications used to handle these items. On Windows 2000 and above, HKCR is a compilation of user-based HKCU\Software\Classes and machine-based HKLM\Software\Classes. If a given value exists in both of the subkeys above, the one in HKCU\Software\Classes takes precedence.[7] The design allows for either machine- or user-specific registration of COM objects. The user-specific classes hive, unlike the HKCU hive, does not form part of a roaming user profile.
HKEY_CURRENT_USER (HKCU)[]
Abbreviated HKCU, HKEY_CURRENT_USER stores settings that are specific to the currently logged-in user.[8] The HKCU key is a link to the subkey of HKEY_USERS that corresponds to the user; the same information is accessible in both locations. On Windows- NT based systems, each user’s settings are stored in their own files called NTUSER.DAT and USRCLASS.DAT inside their own Documents and Settings subfolder (or their own Users subfolder in Windows Vista). Settings in this hive follow users with a roaming profile from machine to machine.
HKEY_LOCAL_MACHINE (HKLM)[]
Abbreviated HKLM, HKEY_LOCAL_MACHINE stores settings that are specific to the local computer.[9] On NT-based versions of Windows, HKLM contains four subkeys, SAM, SECURITY, SOFTWARE and SYSTEM, that are found within their respective files located in the %SystemRoot%\System32\config folder. A fifth subkey, HARDWARE, is volatile and is created dynamically, and as such is not stored in a file. Information about system hardware drivers and services are located under the SYSTEM subkey, while the SOFTWARE subkey contains software and Windows settings.
HKEY_USERS (HKU)[]
Abbreviated HKU, HKEY_USERS contains subkeys corresponding to the HKEY_CURRENT_USER keys for each user profile actively loaded on the machine, though user hives are usually only loaded for currently logged-in users.
HKEY_CURRENT_CONFIG (HKCC)[]
Abbreviated HKCC, HKEY_CURRENT_CONFIG contains information gathered at runtime; information stored in this key is not permanently stored on disk, but rather regenerated at the boot time. It is a link to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Hardware Profiles\Current.
HKEY_PERFORMANCE_DATA[]
This key provides runtime information into performance data provided by either the NT kernel itself or other programs that provide performance data. This key is not displayed in the Registry Editor, but it is visible through the registry functions in the Windows API.
HKEY_DYN_DATA[]
This key is used only on Windows 95, Windows 98 and Windows Me.[10] It contains information about hardware devices, including Plug and Play and network performance statistics. The information in this hive is also not stored on the hard drive. The Plug and Play information is gathered and configured at startup and is stored in memory.[11]
Aliases[]
Aliases in the Windows 9x registry:
Root key | Aliases for |
---|---|
HKEY_CLASSES_ROOT | HKEY_LOCAL_MACHINE\Software\Classes |
HKEY_CURRENT_USER | User’s branch within HKEY_USERS |
HKEY_CURRENT_CONFIG | Hardware profile within HKEY_LOCAL_MACHINE\Config |
Editing[]
Manual editing[]
Windows 3.11 Registry Editor
The Windows registry can be edited manually using programs such as regedit.exe and regedt32.exe.
As a careless change could cause irreversible damage, a backup of the registry before editing is recommended by Microsoft.
A simple implementation of the current registry tool appeared in Windows 3.x, called the «Registration Info Editor» or «Registration Editor». This was basically just a database of applications used to edit embedded OLE objects in documents.
Windows 9x operating systems include REGEDIT.EXE which can be used in Windows and also in real mode MS-DOS.[12] Windows NT introduced permissions for Registry editing. Windows NT 4.0 and Windows 2000 were distributed with both the Windows 9x REGEDIT.EXE program and Windows NT 3.x’s REGEDT32.EXE program. There are several differences between the two editors on these platforms:
- REGEDIT.EXE has a left-side tree view that begins at «My Computer» and lists all loaded hives. REGEDT32.EXE has a left-side tree view, but each hive has its own window, so the tree displays only keys.
- REGEDIT.EXE represents the three components of a value (its name, type, and data) as separate columns of a table. REGEDT32.EXE represents them as a list of strings.
- REGEDIT.EXE supports right-clicking of entries in a tree view to adjust properties and other settings. REGEDT32.EXE requires all actions to be performed from the top menu bar.
- REGEDIT.EXE supports searching for key names, values, or data throughout the entire registry, whereas REGEDT32.EXE only supports searching for key names in one hive at a time.
- Because REGEDIT.EXE was directly ported from Windows 95, it does not support editing permissions. (Permissions do not exist on Windows 9x). Therefore, of the two, only REGEDT32.EXE can access the full functionality of an NT registry.
- REGEDIT.EXE only supports string (REG_SZ), binary (REG_BINARY), and DWORD (REG_DWORD) values. REGEDT32.EXE supports those, plus expandable string (REG_EXPAND_SZ) and multi-string (REG_MULTI_SZ). Attempting to edit unsupported key types with REGEDIT.EXE on Windows 2000 or Windows NT 4.0 will result in irreversible conversion to a supported type.[13]
Windows XP was the first system to integrate these two programs into one, adopting the old REGEDIT.EXE interface and adding the REGEDT32.EXE functionality. The differences listed above are not applicable on Windows XP and newer systems; REGEDIT.EXE is the improved editor, and REGEDT32.EXE is simply a stub that invokes REGEDIT.EXE.
The Registry Editor allows users to perform the following functions:
- Creating, manipulating, renaming and deleting registry keys, subkeys, values and value data
- Importing and exporting .REG files, exporting data in the binary hive format
- Loading, manipulating and unloading registry hive format files (Windows NT-based systems only)
- Setting permissions based on ACLs (Windows NT-based systems only)
- Bookmarking user-selected registry keys as Favorites
- Finding particular strings in key names, value names and value data
- Remotely editing the registry on another networked computer
It is also possible to edit the registry under Linux using the open source Offline NT Password & Registry Editor to edit the files.[14]
.REG files[]
.REG files (also known as Registration entries) are text-based human-readable files for storing portions of the registry. On Windows 2000 and later NT-based operating systems, they contain the string Windows Registry Editor Version 5.00 at the beginning and are Unicode-based. On Windows 9x and NT 4.0 systems, they contain the string REGEDIT4 and are ANSI-based.[15]Template:Failed verification Windows 9x format .REG files are compatible with Windows 2000 and later NT-based systems. The Registry Editor on Windows on these systems also supports exporting .REG files in Windows 9x/NT format. Data is stored in .REG files in the following syntax:[15]
[<Hive Name>\<Key Name>\<Subkey Name>] "Value Name"=<Value type>:<Value data>
The Default Value of a key can be edited by using @ instead of «Value Name»:
@=<Value type>:<Value data>
String values do not require a <Value type> (see example).
For example, to add the values «Value A», «Value B», «Value C», «Value D», and «Value E» to the HKLM\SOFTWARE\Microsoft key,
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft] "Value A"="<String value data>" "Value B"=hex:<Binary data> "Value C"=dword:<DWORD value integer> "Value D"=hex(7):<Multi-string value data> "Value E"=hex(2):<Expandable string value data>
Data from .REG files can be added/merged with the registry by double-clicking these files or using the /s switch in the command line. .REG files can also be used to remove registry data.
To remove a key (and all subkeys, values and data), the key name must be preceded by a minus sign («-«).[15]
For example, to remove the <Key Name> key (and all subkeys, values and data),
[-HKEY_LOCAL_MACHINE\SOFTWARE\<Key Name>]
To remove a value (and its data), the values to be removed must have a minus sign («-«) after the equal sign («=»).[15]
For example, to remove only the «Value A» and «Value B» values (and their data) from the <Key Name> key,
[HKEY_LOCAL_MACHINE\SOFTWARE\<Key Name>] "Value A"=- "Value B"=-
To remove only the (Default) value of the key <Key Name> (and its data),
[HKEY_LOCAL_MACHINE\SOFTWARE\<Key Name>] @=-
Command line editing[]
The registry can be manipulated in a number of ways from the command line. The reg.exe
utility tool is included in Windows XP and later versions of Windows. Alternative locations for legacy versions of Windows include the Resource Kit CDs or the original Installation CD of Windows.
Also, a .REG
file can be imported from the command line with the following command:
regedit.exe /s file
The /s means the file will be silent merged to the Registry. If the /s
parameter is omitted the user will be asked to confirm the operation. In Windows 98, Windows 95 and at least some configurations of Windows XP the /s
switch also causes regedit.exe
to ignore the setting in the registry that allows administrators to disable it. When using the /s
switch Regedit does not return an appropriate return code if the operation fails, unlike reg.exe which does.
The default association for .REG
files in many versions of Microsoft Windows.
Other command line options include a VBScript or JScript together with CScript, WMI or WMIC.exe
and Windows PowerShell.
Registry permissions can be manipulated through the command line using the SubInACL.exe
tool. For example, the permissions on the HKEY_LOCAL_MACHINE\SOFTWARE key can be displayed using:
subinacl /keyreg HKEY_LOCAL_MACHINE\SOFTWARE /display
Programs or scripts[]
The registry can be edited through the APIs of the Advanced Windows 32 Base API Library (advapi32.dll).[16]
List of Registry API functions | |||
---|---|---|---|
RegCloseKey | RegOpenKey | RegConnectRegistry | RegOpenKeyEx |
RegCreateKey | RegQueryInfoKey | RegCreateKeyEx | RegQueryMultipleValues |
RegDeleteKey | RegQueryValue | RegDeleteValue | RegQueryValueEx |
RegEnumKey | RegReplaceKey | RegEnumKeyEx | RegRestoreKey |
RegEnumValue | RegSaveKey | RegFlushKey | RegSetKeySecurity |
RegGetKeySecurity | RegSetValue | RegLoadKey | RegSetValueEx |
RegNotifyChangeKeyValue | RegUnLoadKey |
Many programming languages offer built-in runtime library functions or classes that enable programs to store settings in the registry (e.g. Microsoft.Win32.Registry
in VB.NET and C#, or TRegistry
in Delphi). COM-enabled applications like Visual Basic 6 can use the WSH WScript.Shell
object. Another way is to use the Windows Resource Kit Tool, Reg.exe by executing it from code,[17] although this is considered poor programming practice.
Similarly, scripting languages such as Perl (with Win32::TieRegistry
), Windows PowerShell and Windows Scripting Host also enable registry editing from scripts.
Locations[]
The Registry is stored in several files; depending upon the version of Windows, there will be different files and different locations for these files, but they are all on the local machine. The user-specific HKEY_CURRENT_USER user registry hive is stored in Ntuser.dat inside the user profile. There is one of these per user; if a user has a roaming profile, then this file will be copied to and from a server at logout and login respectively.
Windows NT-based operating systems[]
Windows NT-based systems store the registry in a binary hive format which is the same format that can be exported, loaded and unloaded by the Registry Editor in these operating systems. The following Registry files are stored in %SystemRoot%\System32\Config\:
- Sam – HKEY_LOCAL_MACHINE\SAM
- Security – HKEY_LOCAL_MACHINE\SECURITY
- Software – HKEY_LOCAL_MACHINE\SOFTWARE
- System – HKEY_LOCAL_MACHINE\SYSTEM
- Default – HKEY_USERS\.DEFAULT
- Userdiff – Not associated with a hive. Used only when upgrading operating systems.[18]
The following file is stored in each user’s profile folder:
- %UserProfile%\Ntuser.dat – HKEY_USERS\<User SID> (linked to by HKEY_CURRENT_USER)
For NT and XP, you also have the file
- %UserProfile%\Local Settings\Application Data\Microsoft\Windows\Usrclass.dat (path is localized) – HKEY_USERS\<User SID>_Classes (HKEY_CURRENT_USER\Software\Classes)
For Vista you have the file
- %UserProfile%\AppData\Local\Microsoft\Windows\Usrclass.dat (path is localized) – HKEY_USERS\<User SID>_Classes (HKEY_CURRENT_USER\Software\Classes)
Windows 2000 keeps an alternate copy of the registry hives (.ALT) and attempts to switch to it when corruption is detected.[19] Windows XP and Windows Server 2003 do not maintain a System.alt hive because NTLDR on those versions of Windows can process the System.log file to bring up to date a System hive that has become inconsistent during a shutdown or crash. In addition, the %Windir%\Repair folder contains a copy of the system’s registry hives that were created after installation and the first successful startup of Windows.
Windows 95, 98, and Me[]
The registry files are named USER.DAT and SYSTEM.DAT are stored in the %WINDIR% directory. In Windows Me, Classes.dat was added. Also, each user profile (if profiles are enabled) has its own USER.DAT in profile’s directory.
Windows 3.11[]
The registry file is Reg.dat, system.dat and is stored in the C:\WINDOWS directory.
These files also contain system registry info: user.dat and is stored in the C:\windows\profiles\<username>\user.dat directory.
Backups and recovery[]
Windows supports several methods to back up and restore the registry:
- System Restore can back up the registry and restore it as long as Windows is bootable, or from the Windows Recovery Environment starting with Windows Vista.
- NTBackup can back up the registry as part of the System State and restore it.
- On Windows NT-based systems, the Last Known Good Configuration option in startup menu relinks the HKLM\SYSTEM\CurrentControlSet key, which stores hardware and device driver information.
- Windows 98 and Windows Me include command line (Scanreg.exe) and GUI (Scanregw.exe) registry checker tools to check and fix the integrity of the registry, create up to five automatic regular backups by default and restore them manually or whenever corruption is detected. The registry checker tool backs up the registry, by default, to %Windir%\Sysbckup Scanreg.exe can also run from MS-DOS.
- The Windows 95 CD-ROM included an Emergency Recovery Utility (ERU.exe) and a Configuration Backup Tool (Cfgback.exe) to back up and restore the registry. Additionally Windows 95 backs up the registry to the files system.da0 and user.da0 on every successful boot.
Policy[]
Group policy[]
Windows 2000 and later versions of Windows use Group Policy to enforce Registry settings. Policy may be applied locally to a single computer using GPEdit.msc, or to multiple computers in a domain using gpmc.msc.
Legacy systems[]
With Windows 95, Windows 98, Windows Me and Windows NT, administrators can use a special file to be merged into the registry, called a policy file (POLICY.POL). The policy file allows administrators to prevent non-administrator users from changing registry settings like, for instance, the security level of Internet Explorer and the desktop background wallpaper. The policy file is primarily used in a business with a large number of computers where the business needs to be protected from rogue or careless users.
The default extension for the policy file is .POL.
The policy file filters the settings it enforces by user and by group (a «group» is a defined set of users). To do that the policy file merges into the registry, preventing users from circumventing it by simply changing back the settings.
The policy file is usually distributed through a LAN, but can be placed on the local computer.
The policy file is created by a free tool by Microsoft that goes by the filename poledit.exe for Windows 95/Windows 98 and with a computer management module for NT-based systems.
The editor requires administrative permissions to be run on systems that uses permissions.
The editor can also directly change the current registry settings of the local computer and if the remote registry service is installed and started on another computer it can also change the registry on that computer.
The policy editor loads the settings it can change from .ADM files, of which one is included, that contains the settings the Windows shell provides. The .ADM file is plain text and supports easy localisation by allowing all the strings to be stored in one place.
.INI file virtualization[]
Windows NT kernels support redirection of INI file-related APIs into a virtual file in a Registry location such as HKEY_CURRENT_USER using a feature called «InifileMapping».[20] This functionality was introduced to allow legacy applications written for 16-bit versions of Windows to be able to run under Windows NT platforms on which the System folder is no longer considered an appropriate location for user-specific data or configuration. Non-compliant 32-bit applications can also be redirected in this manner, even though the feature was originally intended for 16-bit applications.
Registry virtualization[]
Windows Vista has introduced limited Registry virtualization, whereby poorly written applications that do not respect the principle of least privilege and instead try to write user data to a read-only system location (such as the HKEY_LOCAL_MACHINE hive), can be redirected to a more appropriate location, without changing the application itself. The operation is transparent to the application, as it does not know that its Registry operations have been directed elsewhere.
Similarly, application virtualization redirects all of an application’s Registry operations to a non-Registry backed location, such as a file. Used together with file virtualization, this approach allows applications to run without being installed on the location machine.
Low integrity processes may also leverage registry virtualisation. For example as Internet Explorer 7 or 8 running in «Protected Mode» on Windows Vista or Windows 7 will automatically redirect registry writes by ActiveX controls to a sandboxed location in order to frustrate some classes of security exploits.
Lastly, the Application Compatibility Toolkit[21] provides shims that can transparently redirect HKEY_LOCAL_MACHINE or HKEY_CLASSES_ROOT Registry operations to HKEY_CURRENT_USER to address «LUA» bugs that cause applications not to work for limited users.
Equivalents in other operating systems[]
In contrast to the Windows registry’s binary-based database model, some other operating systems use separate plain-text files for daemon and application configuration, but group these configurations together for ease of management.
- Under Unix-like operating systems e.g. Linux that follow the Filesystem Hierarchy Standard, system-wide configuration files (information similar to what would appear in HKEY_LOCAL_MACHINE on Windows) are traditionally stored in files in /etc/ and its subdirectories, or sometimes in /usr/local/etc. Per-user information (information that would be roughly equivalent to that in HKEY_CURRENT_USER) is stored in hidden directories and files (that start with a period/full stop) within the user’s home directory. However XDG-compliant applications should refer to the environment variables defined in the Base Directory specification[22].
- Applications running on Apple Inc.’s Mac OS X operating system typically store settings in property list files which are usually stored in each user’s Library folder.
- RISC OS also allows applications to be copied into directories easily, as opposed to the separate installation program that typifies Windows applications. If one wishes to remove the application, it is possible to simply delete the folder belonging to the application.[23] This will often not remove configuration settings which are stored independently from the application, usually within the computer’s !Boot structure, in !Boot.Choices, but potentially anywhere on a network fileserver.
- IBM AIX (a Unix variant) uses a registry component called Object Data Manager (ODM). The ODM is used to store information about system and device configuration. An extensive set of tools and utilities provides users with means of extending, checking, correcting the ODM database. The ODM stores its information in several files, default location is /etc/objrepos.
- The GNOME desktop environment uses a registry-like interface called GConf for storing configuration settings for the desktop and applications. However, in GConf, all application settings are stored in separate files, thereby eliminating a single point of failure. Conversely, this also creates multiple points of failure, and the likelihood of one or more files being destroyed is increased.
- The Elektra Initiative provides an alternative back-end for text configuration files for the Linux operating system, similar to the registry.
- While not an operating system, the Wine compatibility layer, which allows Windows software to run on a Unix-like system, also employs a Windows-like registry as text files in the WINEPREFIX folder: system.reg (HKEY_LOCAL_MACHINE), user.reg (HKEY_CURRENT_USER) and userdef.reg.[24]
Criticism[]
While offering improvements over application-specific .INI files, the organization and implementation of the registry also has potential problems. Criticisms include the following:
- The registry duplicates much of the functionality of the file system.
- Centralizing configurations makes it difficult to back up and recover individual applications.
- Because the Registry structure is contained in files which are not human readable, damage to the registry itself is difficult or impossible to repair.[citation needed] Because information required for loading device drivers is stored in the registry[25], a damaged registry may prevent a Windows system from booting successfully. While damaged configuration files can have the same result to other operating systems, the damage can be more easily repaired by booting to another operating system, and using a text editor.
- Installers and uninstallers become more complicated, because application configuration settings cannot be transferred by simply copying the files that comprise the application.
- Applications that make use of the registry to store and retrieve their settings are unsuitable for use on portable devices used to carry applications from one system to another.
- Since an application’s configuration is centralized away from the application itself, it is often not possible to copy installed applications that use the Registry to another computer. This means that software usually has to be reinstalled from original media on a computer upgrade or rebuild, rather than just copying the user and software folder to the new computer.
- The Windows Registry is said to be a single point of failure.[26][27]
See also[]
- Registry cleaner
- Application virtualization
Notes[]
- ↑ When applications fail to execute because they request more privileges than they require (and are denied those privileges), this is known as a limited user application (LUA) bug.
Footnotes[]
- ↑ «Windows 2000 Registry: Latest Features and APIs Provide the Power to Customize and Extend Your Apps». Retrieved 2007-07-19.
- ↑ «Windows 95 Architecture Components». Microsoft. http://www.microsoft.com/technet/archive/win95/rk31_arc.mspx?mfr=true. Retrieved 2008-04-29. «The following table shows other difficulties or limitations caused by using INI files that are overcome by using the Registry.»
- ↑ Raymond Chen, «Why do registry keys have a default value?»
- ↑ «Registry hives». Retrieved 2007-07-19.
- ↑ Why is a registry file called a «hive»?
- ↑ «Designed for Windows XP Application Specification». Microsoft. 2002-08-20. Retrieved 2009-04-08.
- ↑ «Description of the Microsoft Windows registry». Retrieved 2008-09-25.
- ↑ «HKEY_CURRENT_USER». Microsoft. 2009. Retrieved 2009-04-08.
- ↑ «HKEY_LOCAL_MACHINE». Microsoft. 2009. Retrieved 2009-04-08.
- ↑ Description of the HKEY_DYN_DATA Registry Key in Windows 95, Windows 98, and Windows 98 SE
- ↑ A Closer Look at HKEY_DYN_DATA
- ↑ Using Registry Editor in Real Mode
- ↑ Microsoft’s Windows 2000 Security Hardening Guide version 1.3, published May 15, 2003
- ↑ Offline Registry Editor user manual/doc
- ↑ 15.0 15.1 15.2 15.3 How to add, modify, or delete registry subkeys and values by using a registration entries (.reg) file
- ↑ «Reading and Writing Registry Values with Visual Basic». Retrieved 2007-07-19.
- ↑ «REG command in Windows XP». Retrieved 2007-07-19.
- ↑ Microsoft Corporation
- ↑ «Inside the Registry». Retrieved 2007-12-28.
- ↑ «Chapter 26 — Initialization Files and the Registry». Microsoft. Retrieved 2008-03-03.
- ↑ «Microsoft Application Compatibility Toolkit 5.0». Microsoft. Retrieved 2008-07-26.
- ↑ «XDG Base Directory Specification».
- ↑ «RISC OS tour». Retrieved 2007-07-19.
- ↑ 3.2. Using the Registry and Regedit (Wine User Guide)
- ↑ http://technet.microsoft.com/en-us/library/cc959506.aspx
- ↑
«The cranky user: Storing configuration data». «The Windows registry […] has created a nightmarish single point of failure for configuration data.» - ↑
«Windows registry design». «The Windows registry is a single point of failure.»
References[]
- Russinovich, Mark E.; Solomon, David A. (2005). Microsoft Windows Internals (Fourth Edition ed.). Microsoft Press. pp. 183–236. ISBN 978-0-7356-1917-3.
External links[]
- Windows Registry info & reference in the MSDN Library
- Security Accounts Manager — low-level registry and SAM information
- REGLN Utility — Create or delete symbolic links in the Windows Registry
- Offline NT Password & Registry Editor — open-source program and boot disk to reset/change Windows passwords and edit Windows registries under Linux
Microsoft Windows components | |
Core |
|
Management |
|
Applications |
|
Games |
|
Kernel |
|
Services |
|
File Systems |
|
Server |
|
Architecture |
|
Security |
|
Compatibility |
|
Edit — View |
The Windows Registry is the central database in your computer. It contains all the instructions and settings (related to hardware and software) your computer needs to perform any task. Frequently your computer accesses the registry. To help you gain more knowledge on the science of registry, in this article we discuss about the basic structure of the registry.
Once you open the Windows Registry you can see the entire registry organized into 5 folders (technically called ‘keys’). Each of these keys again contains sub keys and values (similar to files) within them. So the description of the five root keys of Windows Registry is mentioned below.
The 5 Registry Root Keys of The Windows Registry:
1. HKEY_CLASSES_ROOT (HKCR)
The HKEY_CLASSES_ROOT, abbreviated as HKCR is a registry root key, whose hive has all the information of the file name extensions and OLE (Object Linking and Embedding). There are thousands of keys within this hive. All of these are for sake of understanding classified into these classes:
- Each key is a file name extension with the information about the default program with which files of that format are accessed. You can modify the program that is set as default here. But owing to all the complexity this process carries, we recommend not doing so. Also the OLE technology helps in linking and embedding objects and programs. But the complexity involved is definitely a bottleneck though.
- The remaining keys in this hive are ProgID, CLSID and IID. These keys are related to technical aspects of programming and will be discussed later on.
2. HKEY_CURRENT_USER (HKCU)
This registry root key contains all the settings related to the user who is currently logged into the computer. Right from the appearance aspect to how the mouse pointer behaves, everything can be controlled via this hive. Usually in most of the Windows operating systems all these settings are available in the following keys:
- Console Key
- Control Panel Key
- Environment Key
- Network Key
- Software Subtree
(Source: technet.microsoft.com)
3. HKEY_LOCAL_MACHINE (HKLM)
This is one of the most accessed registry hives. This registry root key contains all the information about the hardware and software of the system. It includes the bus system used, the hard drive technology, the operating system details and everything else about your computer.
This entire information is not a part of the hard drive but is stored in the system memory, mapping all the sub keys. There actually can be in depth discussion of the science of the HKLM but is out of scope of this article.
4. HKEY_USERS (HKU)
In this registry is the information on settings made by various users on the computers, many a time the values represented by the HKU and HKCU are similar. For better understanding, we can interpret it to be a superset of the HKEY_CURRENT_USER registry root keys.
5. HKEY_CURRENT_CONFIGURATION (HKCC)
The HKCC is the registry root key which contains information about the hardware which is currently used by the computer. It is most often empty and gets activated at boot time, during which it loads the ‘hardware profiles’ sub key of the HKLM.
These are the registry root keys being used in the Windows 8’s registry. Some other additional root keys like the HKEY_DYN_DATA (HKDD) used to be present in the earlier versions of Windows.
Ранее уже было сказано, что системный реестр – это иерархическая база данных, информация в которой распределяется по нескольким уровням (их может быть до шести). На первом уровне расположены ветви (Hive Keys). Всего их пять, название каждой из которых начинается с английской аббревиатуры HKEY_. За символом подчеркивания следует название ветви:
* HKEY_CLASSES_ROOT
* HKEY_CURRENT_USER
* HKEY_LOCAL_MACHINE
* HKEY_USERS
* HKEY_CURRENT_CONFIG
Есть еще и шестая ветвь – HKEY_DYN_DATA. В ней содержатся динамические данные о состоянии устройств, установленных на компьютере. Данные этого раздела формируются и изменяются операционной системой в процессе загрузки и в виде файлов не сохраняются.
На втором уровне располагаются разделы или ключи реестра (Registry Keys), на третьем – подразделы (Subkeys) и на четвертом и далее – параметры (Values). Если взять за аналогию иерархическую файловую структуру, то уровни реестра можно отобразить следующим образом:
Ключи системного реестра функционально можно разделить на две условные категории: определяемые системой, то есть те, имена которых назначены операционной системой, причем изменение этих имен может привести к отказу или сбоям в работе Windows, и определяемые пользователем — имена этих ключей могут быть изменены администратором компьютера, и такие изменения не приведут к каким-либо фатальным последствиям.
Так же как и имена ключей, имена подразделов могут быть определены системой или пользователем, причем в первом случае их изменение способно привести к сбоям в работе Windows, а во втором случае — нет.
Структура системного реестра 64-разрядной версии Microsoft Windows несколько отличается от архитектуры реестра 32-разрядных версий Windows . Он имеет два независимых раздела: в одном содержатся данные, относящиеся к 32-разрядным компонентам операционной системы, в другом — все сведения по 64-разрядным компонентам, — причем ключи и ветви обоих разделов имеют практически одинаковые наименования и обозначения.
Рассмотрим подробнее, какие данные находятся в том или ином разделе.
HKEY_CLASSES_ROOT (HKCR)
Этот раздел включает в себя ряд подразделов, в которых содержатся сведения о расширениях всех зарегистрированных в системе типов файлов и данные о COM-серверах, зарегистрированных на компьютере. Данные этого раздела нужны при открытии файлов по двойному щелчку мыши или операций drag-and-drop. Кроме того, раздел HKEY_CLASSES_ROOT предоставляет объединенные данные программам, написанным под ранние версии Windows.
HKEY_CURRENT_USER (HKCU)
Эта ветвь реестра хранит настройки персональной оболочки пользователя, совершающего вход в операционную систему (меню «Пуск», рабочий стол и т. д.). В ее подразделах находится информация о переменных окружения, группах программ данного пользователя, настройках Рабочего стола, цветах экрана, сетевых соединениях, принтерах и дополнительных настройках приложений. Эта информация берется из подраздела Security ID (SID) ветви HKEY_USERS для текущего пользователя. Фактически, в данной ветви собраны все сведения, относящиеся к профилю пользователя, работающего с Windows в настоящий момент.
HKEY_LOCAL_MACHINE (HKLM)
Раздел содержит информацию об установленном программном обеспечении, его настройках, драйверах. Здесь же – информация, относящаяся к операционной системе и оборудованию, например тип шины компьютера, общий объем доступной памяти, список загруженных в данный момент времени драйверов устройств, а также сведения о загрузке Windows. Данная ветвь включает наибольшее количество информации в системном реестре и нередко используется для тонкой настройки аппаратной конфигурации компьютера. Хранящиеся в этой ветви данные справедливы для всех профилей, зарегистрированных в системе пользователей.
HKEY_USERS (HKU)
Если раздел HKEY_CURRENT_USER содержит настройки текущего пользователя, то данный раздел хранит настройки Windows для всех пользователей. В его подразделах содержится информация обо всех профилях пользователей, а один из подразделов всегда соотносится с разделом HKEY_CURRENT_USER (через параметр Security ID (SID) пользователя). Другой подраздел, HKEY_USERS\DEFAULT, содержит информацию о настройках системы в момент времени, предшествующий началу сеанса текущего пользователя.
HKEY_CURRENT_CONFIG (HKCC)
В этой ветви содержится информация о профиле оборудования, используемом локальным компьютером при запуске системы. Профили оборудования позволяют выбрать драйверы поддерживаемых устройств для заданного сеанса работы.
- Home
- Blog
-
Windows Registry Structure: Understanding Keys, Values, and Hives in Windows Registry
/
/
On Microsoft Windows operating systems, the Windows Registry is a hierarchical database that holds configuration settings and options. It includes settings for both low-level operating system components and programmes running on the platform: the registry is used by the kernel, device drivers, services, SAM, user interface, and third-party applications. The registry also allows you to access counters for system performance profiling.
The registry contains two basic elements: Keys and Values. Then there is also the concept of Hives. We’ll be exploring these in this blog post.
Registry Keys
Each key can have subkeys, which can contain further subkeys, and so on. Registry keys are similar to folders in that they can contain values as well as subkeys. Keys are addressed using a syntax similar to that of Windows path names, with backslashes used to signify hierarchy levels. Each subkey must have a name, which must be a non-empty string that does not contain any backslashes or null characters and is case insensitive.
Only a known root key handle (which is anonymous but whose effective value is a constant numeric handle) that is mapped to the content of a registry key preloaded by the kernel from a stored “hive,” or to the content of a subkey within another root key, or mapped to a registered service or DLL that provides access to its contained subkeys and values can access the registry key hierarchy.
HKEY_LOCAL_MACHINE Software Microsoft Windows refers to the subkey “Windows” of the subkey “Microsoft” of the subkey “Software” of the HKEY_LOCAL_MACHINE root key.
There are seven predefined root keys:
-
HKEY_LOCAL_MACHINE or HKLM
-
HKEY_CURRENT_CONFIG or HKCC (only in Windows 95/98/ME and NT-based versions of Windows)
-
HKEY_CLASSES_ROOT or HKCR
-
HKEY_CURRENT_USER or HKCU
-
HKEY USERS or HKU
-
HKEY PERFORMANCE DATA (only in NT-based versions of Windows, but invisible in the Windows Registry Editor)
-
HKEY_DYN DATA (only in Windows 95/98/ME, and visible in the Windows Registry Editor)
All registry keys may be controlled by access control lists (ACLs) based on user privileges, security tokens acquired by apps, or system security policies imposed by the system, just like other files and services in Windows. (These limitations may be set by the system and configured by local system administrators or domain administrators.) Users, programmes, services, and remote systems may only see certain parts of the hierarchy or different hierarchies from the same root keys.
HKEY_LOCAL_MACHINE (HKLM)
The key indicated by HKLM is not saved on disc, but rather in memory by the system kernel, which uses it to map all other subkeys. Additional subkeys cannot be created by applications. This key has four subkeys, “SAM”, “SECURITY”, “SYSTEM”, and “SOFTWARE”, which are loaded at boot time within their respective files in the %SystemRoot%System32config folder on NT-based versions of Windows. The fifth subkey, “HARDWARE,” is volatile and dynamically formed, thus it is not saved in a file (it exposes a view of all the currently detected Plug-and-Play devices). The kernel maps the sixth subkey in memory and populates it with boot configuration data (BCD) for Windows Vista, Windows Server 2008, Windows Server 2008 R2, and Windows 7.
HKLMSAM Key
For most users, this key seems to be empty (unless they are granted access by administrators of the local system or administrators of domains man- aging the local system). It’s used to refer to all “Security and Accounts Management” (SAM) databases for all domains into which the local system has been administratively authorised or configured (including the running system’s local domain, which has a subkey named “SAM” in its SAM database; additional subkeys will be created as needed, one for each supplementary domain).
Each SAM database contains all built-in accounts (mostly group aliases) and configured accounts (users, groups and their aliases, including guest accounts and administrator accounts) created and configured on the respective domain, for each account in that domain, it notably contains the user name which can be used to log on that domain, the internal unique user identifier in the domain, their cryptographically hashed password on that domain, the location of storage of their user registry hive, various status flags (for example if the account can be enumerated and be visible in the logon prompt screen), and the list of domains (including the local domain) into which the account was configured.
HKLMSECURITY Key
This key is linked to the Security database of the domain into which the current user is logged on (if the user is logged on the local system domain, this key will be linked to the registry hive stored by the local machine and managed by local system administrators or by the builtin “System” account and Windows installers). It is usually empty for most users (unless they are granted access by users with administrative privileges). The kernel will utilise it to read and enforce the security policy that applies to the cur- rent user and all of their programmes and operations. It also has a “SAM” subkey that is dynamically linked to the domain’s SAM database, where the current user is logged on.
HKLMSYSTEM Key
Users with administrative access on the local system are usually the only ones who may write to this key. It contains data for the secure random number generator (RNG), a list of currently mounted devices with a file system, several numbered “HKLMSYSTEMControl Sets” containing alter- native configurations for system hardware drivers and services running on the local system (including the currently used one and a backup), a “HKLMSYSTEMSelect” subkey containing the status of these Control Sets, and a “HKLMSYSTEMCurrentControlSelect” subkey containing the status of these Control is dynamically linked at boot time to the Control Set which is currently used on the local system.
Each configured Control Set contains:
-
“Enum” subkey enumerating all known Plug-and-Play devices and associating them with installed system drivers (and storing the device- specific configurations of these drivers).
-
“Services” subkey listing all installed system drivers (with non-device- specific configuration, and the enumeration of devices for which they are instantiated) and all programs running as services (how and when they can be automatically started).
-
“Control” subkey organising the various hardware drivers and programs running as services and all other system-wide configuration.
-
“Hardware Profiles” subkey enumerating the various profiles that have been tuned (each one with “System” or “Software” settings used to modify the default profile, either in system drivers and services or in the applications) as well as the “Hardware ProfilesCurrent” subkey which is dynamically linked to one of these profiles.
HKLMSOFTWARE Subkey
The software and Windows settings are stored on this key (in the default hardware profile). The majority of changes are made by application and system installers. It’s organised by the software vendor (with subkeys for each), but it also has a “Windows” subkey for some Windows user inter- face settings, a “Classes” subkey for all registered associations from file extensions, MIME types, Object Classes IDs, and interfaces IDs (for OLE, COM/DCOM, and ActiveX) to the installed applications or DLLs that may be handling these types on the local machine (however, these associations are configurable for each user, see below (including the central certificates store used for authenticating, authorising or disallowing remote systems or services running outside of the local network domain).
HKEY_CURRENT_CONFIG (HKCC)
This key stores information obtained during runtime; data in this key is not permanently kept on disc, but is regenerated at boot time. It’s a handle to the key “HKEY LOCAL MACHINESystemCurrentControlSetHardware ProfilesCurrent,” which is empty at first but is filled in at boot time by loading one of the other subkeys in “HKEY LOCAL MACHINESystemCur- rentControlSetHardware Profiles.”
HKEY_CLASSES_ROOT (HKCR)
This key stores information about registered programmes, including as file associations and OLE Object Class IDs, and links them to the applications that deal with them. HKCR is a collection of user-based HKCUSoftware- Classes and machine-based HKLMSoftwareClasses on Windows 2000 and later. If the same value appears in both subkeys, the one in HKCUSoftware- Classes takes precedence. The design allows COM objects to be registered by either the machine or the user. Unlike the HKCU hive, the user-specific classes hive is not part of a roaming user profile.
HKEY_USERS (HKU)
User hives are normally only loaded for presently logged-in users and contain subkeys matching to the HKEY CURRENT USER keys for each user profile actively loaded on the PC.
HKEY_CURRENT_USER (HKCU)
This key contains parameters specific to the user who is presently logged in. The HKCU key is a link to the HKEY USERS subkey that belongs to the user; both places have the identical information. Each user’s settings are stored in their own NTUSER.DAT and USRCLASS.DAT files under their own Documents and Settings subdirectory on Windows NT-based systems (or their own Users sub folder in Windows Vista and Windows 7). This hive’s settings are carried across from machine to machine by users with a roaming profile.
HKEY_PERFORMANCE_DATA
This key enables access to performance data provided by the NT kernel or by operating system drivers, programmes, and services that offer performance statistics. This key is not stored in any hive and is not visible in the Registry Editor, but it can be accessed via the Windows API registry functions, or in a simplified view via the Task Manager’s Performance tab (for a limited set of performance data on the local system), or via more advanced control panels (such as the Performances Monitor or the Performances Analyzer which allows collecting and logging these data, including from remote systems).
HKEY_DYN_DATA
Only Windows 95, Windows 98, and Windows Me supported this key. It includes Plug & Play and network performance statistics, as well as information about hardware devices. The data in this hive isn’t saved on the hard drive either. At launch, the Plug and Play information is gathered and configured, then saved in memory.
Values
Name/data pairs are kept as registry values in keys. The terms registry values and registry keys are not interchangeable. In a registry key, each registry value has its own name, regardless of letter case. The Windows API functions that query and update registry information isolate the value names from the key path and/or handle that identifies the parent key. Registry variables with backslashes in their names make it harder to distinguish them from their key paths when using numerous legacy Windows Registry API actions (whose usage is deprecated in Win32).
Although each registry key is similar to an associative array, the name portion of each registry value is referred to as a “key” in standard parlance. The phrases are a relic from the 16-bit registry of Windows 3, which per- mitted registry keys to have only one unnamed value rather than arbitrary name/data combinations (which had to be a string). The registry was treated as a single associative array, with a hierarchy of registry keys (in both the registry and dictionary senses) and all registry values being strings. When the 32-bit registry was introduced, it also contained the ability to create several named values per key, which changed the semantics of the names. To retain compatibility with earlier behaviour, each registry key may have a “default” value, which is the empty string.
Each value can have any sort of data, regardless of length or encoding, as well as a symbolic type (given as a numeric constant) that indicates how to read it.
The standard types are:
Type ID | Symbolic type name | Meaning and encoding of the data stored in the registry value |
0 | REG_NONE | No type ( the stored value , if any ) |
1 | REG_SZ | A string value , normally stored and exposed in UTF – 16LE ( when using the Unicode version of Win32 API functions ) , usually terminated by a null character |
2 | REG_EXPAND_SZ | An ” expandable ” string value that can contain environment variables , normally stored and exposed in UTF – 16LE , usu ally terminated by a null character |
3 | REG_BINARY | Binary data ( any arbitrary data ) |
4 | REG_DWORD / REG_DWORD_LITTLE_ENDIAN | ADWORD value , a 32 – bit unsigned integer ( numbers between 0 and 4.294,967,295 [ 232-1 ] ) ( little – endian ) |
5 | REG_DWORD_BIG_ENDIAN | ADWORD value , a 32 – bit unsigned integer ( numbers between 0 and 4,294,967,295 [ 232 -1 ] ) ( big – endian ) |
6 | REG_LINK | A symbolic link ( UNICODE ) to another registry key , specifying a root key and the path to the target key |
7 | REG_MULTI_SZ | A multi – string value , which is an ordered list of non – empty strings , normally stored and exposed in UTF – 16LE , each one terminated by a null character , the list being normally terminated by a second null character . |
8 | REG_RESOURCE_LIST | A resource list ( used by the Plug – n – Play hardware enumeration and configuration ) |
9 | REG_FULL_RESOURCE_DESCRIPTOR | A resource descriptor ( used by the Plug – n – Play hardware enumeration and configuration ) |
10 | REG_RESOURCE_REQUIREMENTS_LIST | A resource requirements list ( used by the Plug – n – Play hardware enumeration and configuration ) |
11 | REG_QWORD / REG_QWORD_LITTLE_ENDIAN | AQWORD value , a 64 – bit integer ( either big – or little – endian , or unspecified ) ( Introduced in Windows 2000 ) |
Hives
The Registry is divided into several logical divisions, or “hives” (the word hive constitutes an in-joke). Hives are named after their Windows API definitions, which all start with “HKEY.” They are usually abbreviated to a three- or four-letter abbreviation that begins with “HK” (e.g. HKCU and HKLM). They are predefined handles (with known constant values) to specific keys that are either maintained in memory, stored in hive files stored in the local file system and loaded by the system kernel at boot time and then shared (with various access rights) among all processes running on the local system, or loaded and mapped in all processes started in a user session when the user logs on the system.
The HKEY LOCAL MACHINE (local machine-specific configuration data) and HKEY CURRENT USER (user-specific configuration data) nodes are similar in structure; user applications typically look up their settings by first looking in “HKEY CURRENT USER Software Vendor’s name Application’s name VersionSetting name,” and if that doesn’t work, look in the same location under the HKEY LOCAL MACHINE key. The opposite may be true for administrator-enforced policy settings, where HKLM may take precedence over HKCU. The Windows Logo Program includes precise standards for where different sorts of user data can be stored, as well as following the principle of least privilege so that administrator-level access is not necessary to utilise an application.
We hope that this series takes away the fear that people generally have when they are dealing with the Windows Registry. If you figure out any interesting hacks, please feel free to let us know. We might add more more hacks. Thanks for reading this post. Please share this post and help secure the digital world. Visit our website, thesecmaster.com, and our social media page on Facebook, LinkedIn, Twitter, Telegram, Tumblr, Medium, and Instagram and subscribe to receive updates like this.
You may also like these articles:
Arun KL
Arun KL is a cybersecurity professional with 15+ years of experience in IT infrastructure, cloud security, vulnerability management, Penetration Testing, security operations, and incident response. He is adept at designing and implementing robust security solutions to safeguard systems and data. Arun holds multiple industry certifications including CCNA, CCNA Security, RHCE, CEH, and AWS Security.
Если требуется хранить какую-то информацию, то частенько для этого используется реестр. Реестр Windows представляет собой базу данных, которая хранит данные операционной системы Windows, служб, а так же приложений, в том числе и ваших.
Структура и ключи реестра
Основными элементами реестра являются: ключи и значения, а данные представлены и структурированы в виде дерева.
Дерево имеет 5 корневых ключей реестра (root keys)
Вообще корневых ключей: 7, но многие из них устарели и уже не используются в современном мире.
HKEY_CURRENT_CONFIG — (Win98 и NT-разрядных версий Windows)
HKEY_PERFORMANCE_DATA (для NT-разрядных версий Windows, нельзя увидеть в редакторе реестра Windows)
HKEY_DYN_DATA (Win 9x/Me)
Каждый корневой ключ реестра может содержать любое количество вложенных разделов и подразделов (Subkeys), но при этом есть ограничение по вложенности (не более 512 уровней).
В свою очередь каждый subkeys может содержать любое количество параметров.
Параметр имеет: имя(name), тип(type) и значение(value)
Где хранятся файлы реестра?
файл реестра windows представлен в виде нескольких файлов, которые хранятся в папке config
C:\WINDOWS\system32\config
Каждый файл реестра хранит информацию из определенного раздела реестра. Так же существует ещё несколько файлов, которые хранятся в основной папке пользователя, так например файл NTUSER.dat, в котором храниться профиль текущего пользователя, об это чуть позднее.
Имя файла | Раздел реестра | Описание |
SAM | HKEY_LOCAL_MACHINE\SAM | SAM |
SECURITY | HKEY_LOCAL_MACHINE\SECURITY | Безопасность |
software | HKEY_LOCAL_MACHINE\SOFTWARE | Софт |
system | HKEY_LOCAL_MACHINE\SYSTEM | Система |
default | HKEY_LOCAL_MACHINE\DEFAULT | Параметры по умолчанию |
Как открыть реестр в windows?
Для работы с реестром существует множество программ, одна из них носит имя regedit, она присутствует во всех версиях операционной системы Windows. С помощью неё можно осуществлять редактирование, просмотр, создание разделов, параметром и многое другое.
Путь к файлу программы regedit
C:\WINDOWS\regedit.exe
Чтобы открыть реестр нужно проделать следующие действия:
Нажмите на кнопку «Пуск» -> найдите в меню пункт «Выполнить»
затем введите: regedit, либо используйте горячие клавиши Win+R
кнопка Win расположена между Ctrl и Alt
Работа с реестром используя язык C#
.NET предлагает несколько классов для работы с реестром, один из них
class Registry
В проекте обращаться к данному классу можно, как по полному имени Microsoft.Win32.Registry, либо использовать using Microsoft.Win32;
Данный класс позволяет получить доступ ко всем корневым ключам реестра (root keys).
Перед тем как создать или обратиться к какому-нибудь разделу или подразделу, необходимо воспользоваться этим классом для выбора корневого ключа.
поле | root key |
ClassesRoot | HKEY_CLASSES_ROOT |
CurrentConfig | HKEY_CURRENT_CONFIG |
CurrentUser | HKEY_CURRENT_USER |
Users | HKEY_USERS |
PerformanceData | HKEY_PERFORMANCE_DATA |
DynData | HKEY_DYN_DATA.LocalMachine |
PerformanceData | HKEY_PERFORMANCE_DATA |
Пример на языке c#:
Выбираем root keys CurrentUser, тем самым открываем root ключ HKEY_CURRENT_USER;
RegistryKey regKey = Registry.CurrentUser;
Для дальнейшего перемещения по реестру используется класс RegistryKey, с помощью него можно добавлять, удалять разделы и подразделы, а так же создавать параметры и получать их значения.
Более подробно об этих классах поговорим в следующей статье.
Читайте также:
- c# Работа с TreeView. Часть 2
- Выделение элемента при наведении мышкой в WebBrowser
- Добавление сборки Microsoft.Office.Interop.Excel