Skip to content

Commit 7c8a456

Browse files
CopilotBillWagner
andcommitted
Add registry key creation documentation with permissions guidance
Co-authored-by: BillWagner <[email protected]>
1 parent a1bfceb commit 7c8a456

File tree

4 files changed

+189
-0
lines changed

4 files changed

+189
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
title: "How to create a key in the registry"
3+
description: Learn how to create registry keys in C#, including important permissions considerations and security requirements for registry access.
4+
ms.date: 01/16/2025
5+
helpviewer_keywords:
6+
- "registry keys [C#]"
7+
- "registries [C#], creating keys"
8+
- "permissions [C#], registry"
9+
- "Windows Registry [C#]"
10+
ms.topic: how-to
11+
---
12+
# How to create a key in the registry (C# Programming Guide)
13+
14+
This example creates a key in the current user's registry and stores a value in it. This example demonstrates how to work with the Windows Registry using C#, including important considerations about permissions and security.
15+
16+
## Prerequisites and Permissions
17+
18+
Before working with the Windows Registry, it's important to understand the permission requirements:
19+
20+
- **Administrator privileges**: Some registry operations require elevated permissions. Writing to `HKEY_LOCAL_MACHINE` or other system-wide registry hives typically requires administrator privileges.
21+
- **User-specific access**: Writing to `HKEY_CURRENT_USER` generally doesn't require administrator privileges and is the recommended approach for application settings.
22+
- **Production considerations**: Applications should be designed to work without requiring administrator privileges for routine operations.
23+
24+
## Example
25+
26+
The following example creates a key under `HKEY_CURRENT_USER`, which is accessible without administrator privileges:
27+
28+
:::code language="csharp" source="snippets/how-to-create-a-key-in-the-registry/Program.cs" id="CreateRegistryKey":::
29+
30+
## Robust Programming
31+
32+
A more robust version should include error handling and proper resource disposal:
33+
34+
:::code language="csharp" source="snippets/how-to-create-a-key-in-the-registry/Program.cs" id="RobustRegistryAccess":::
35+
36+
## Registry Locations and Permissions
37+
38+
Different registry locations have different permission requirements:
39+
40+
| Registry Hive | Permission Required | Use Case |
41+
|---------------|-------------------|----------|
42+
| `HKEY_CURRENT_USER` | User permissions | User-specific settings |
43+
| `HKEY_LOCAL_MACHINE` | Administrator | System-wide settings |
44+
| `HKEY_CLASSES_ROOT` | Administrator | File associations, COM registration |
45+
46+
## Best Practices for Applications
47+
48+
When designing applications that use the registry:
49+
50+
1. **Prefer user-specific storage**: Use `HKEY_CURRENT_USER` for application settings when possible.
51+
2. **Handle permission failures gracefully**: Your application should continue to function even if registry access fails.
52+
3. **Consider alternatives**: For many scenarios, configuration files or application data folders are better choices than the registry.
53+
4. **Use read-only access when possible**: Open registry keys with the minimum required permissions.
54+
55+
## Security Considerations
56+
57+
- Always validate data before writing to the registry
58+
- Be cautious about what information you store in the registry, as it might be accessible to other applications
59+
- Consider the security implications of storing sensitive information in the registry
60+
61+
## See also
62+
63+
- <xref:Microsoft.Win32.Registry?displayProperty=nameWithType>
64+
- <xref:Microsoft.Win32.RegistryKey?displayProperty=nameWithType>
65+
- [Security and the Registry (Visual Basic)](/dotnet/visual-basic/developing-apps/programming/computer-resources/security-and-the-registry)
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
using Microsoft.Win32;
2+
using System.Runtime.Versioning;
3+
4+
[SupportedOSPlatform("windows")]
5+
class Program
6+
{
7+
static void Main()
8+
{
9+
if (!OperatingSystem.IsWindows())
10+
{
11+
Console.WriteLine("This example requires Windows operating system.");
12+
return;
13+
}
14+
15+
// <CreateRegistryKey>
16+
// Create a registry key under HKEY_CURRENT_USER
17+
// This does not require administrator privileges
18+
RegistryKey userKey = Registry.CurrentUser.CreateSubKey("TestApp");
19+
20+
// Set a value in the registry key
21+
userKey.SetValue("LastRun", DateTime.Now);
22+
userKey.SetValue("UserName", Environment.UserName);
23+
24+
// Close the key
25+
userKey.Close();
26+
27+
Console.WriteLine("Registry key created successfully under HKEY_CURRENT_USER\\TestApp");
28+
// </CreateRegistryKey>
29+
30+
Console.WriteLine("\nPress any key to run the robust example...");
31+
Console.ReadKey();
32+
33+
// <RobustRegistryAccess>
34+
try
35+
{
36+
// Open or create a registry key with error handling
37+
using (RegistryKey robustKey = Registry.CurrentUser.CreateSubKey("TestApp"))
38+
{
39+
if (robustKey != null)
40+
{
41+
// Store application settings
42+
robustKey.SetValue("ConfigVersion", "1.0");
43+
robustKey.SetValue("EnableNotifications", true);
44+
robustKey.SetValue("MaxRetries", 3);
45+
46+
Console.WriteLine("Application settings saved to registry.");
47+
48+
// Read back the values to verify
49+
string? version = robustKey.GetValue("ConfigVersion") as string;
50+
bool notifications = (bool)(robustKey.GetValue("EnableNotifications") ?? false);
51+
int retries = (int)(robustKey.GetValue("MaxRetries") ?? 0);
52+
53+
Console.WriteLine($"Config Version: {version}");
54+
Console.WriteLine($"Notifications Enabled: {notifications}");
55+
Console.WriteLine($"Max Retries: {retries}");
56+
}
57+
else
58+
{
59+
Console.WriteLine("Failed to create or access registry key.");
60+
}
61+
}
62+
}
63+
catch (UnauthorizedAccessException)
64+
{
65+
Console.WriteLine("Access denied. The application doesn't have permission to access this registry key.");
66+
}
67+
catch (System.Security.SecurityException)
68+
{
69+
Console.WriteLine("Security error. The application doesn't have permission to access the registry.");
70+
}
71+
catch (Exception ex)
72+
{
73+
Console.WriteLine($"An error occurred: {ex.Message}");
74+
}
75+
// </RobustRegistryAccess>
76+
77+
// Demonstrate the difference in permission requirements
78+
Console.WriteLine("\nTrying to access HKEY_LOCAL_MACHINE (may require admin privileges):");
79+
DemonstrateLocalMachineAccess();
80+
}
81+
82+
[SupportedOSPlatform("windows")]
83+
static void DemonstrateLocalMachineAccess()
84+
{
85+
try
86+
{
87+
// This will likely fail without administrator privileges
88+
using (RegistryKey machineKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\TestApp"))
89+
{
90+
if (machineKey != null)
91+
{
92+
machineKey.SetValue("SystemSetting", "value");
93+
Console.WriteLine("Successfully wrote to HKEY_LOCAL_MACHINE");
94+
}
95+
}
96+
}
97+
catch (UnauthorizedAccessException)
98+
{
99+
Console.WriteLine("Access denied to HKEY_LOCAL_MACHINE. Administrator privileges required.");
100+
}
101+
catch (System.Security.SecurityException)
102+
{
103+
Console.WriteLine("Security error accessing HKEY_LOCAL_MACHINE. Administrator privileges required.");
104+
}
105+
catch (Exception ex)
106+
{
107+
Console.WriteLine($"Error accessing HKEY_LOCAL_MACHINE: {ex.Message}");
108+
}
109+
}
110+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
</Project>

docs/csharp/toc.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,10 @@ items:
659659
href: programming-guide/generics/differences-between-cpp-templates-and-csharp-generics.md
660660
- name: Generics in the Run Time
661661
href: programming-guide/generics/generics-in-the-run-time.md
662+
- name: File system and registry
663+
items:
664+
- name: "How to create a key in the registry"
665+
href: programming-guide/file-system/how-to-create-a-key-in-the-registry.md
662666
- name: Other C# documentation
663667
items:
664668
- name: C# language reference

0 commit comments

Comments
 (0)