Skip to content

Add registry key creation documentation with permissions guidance #47686

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
title: "How to create a key in the registry"
description: Learn how to create registry keys in C#, including important permissions considerations and security requirements for registry access.
ms.date: 01/16/2025
helpviewer_keywords:
- "registry keys [C#]"
- "registries [C#], creating keys"
- "permissions [C#], registry"
- "Windows Registry [C#]"
ms.topic: how-to
---
# How to create a key in the registry (C# Programming Guide)

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.

## Prerequisites and Permissions

Before working with the Windows Registry, it's important to understand the permission requirements:

- **Administrator privileges**: Some registry operations require elevated permissions. Writing to `HKEY_LOCAL_MACHINE` or other system-wide registry hives typically requires administrator privileges.
- **User-specific access**: Writing to `HKEY_CURRENT_USER` generally doesn't require administrator privileges and is the recommended approach for application settings.
- **Production considerations**: Applications should be designed to work without requiring administrator privileges for routine operations.

## Example

The following example creates a key under `HKEY_CURRENT_USER`, which is accessible without administrator privileges:

:::code language="csharp" source="snippets/how-to-create-a-key-in-the-registry/Program.cs" id="CreateRegistryKey":::

## Robust Programming

A more robust version should include error handling and proper resource disposal:

:::code language="csharp" source="snippets/how-to-create-a-key-in-the-registry/Program.cs" id="RobustRegistryAccess":::

## Registry Locations and Permissions

Different registry locations have different permission requirements:

| Registry Hive | Permission Required | Use Case |
|---------------|-------------------|----------|
| `HKEY_CURRENT_USER` | User permissions | User-specific settings |
| `HKEY_LOCAL_MACHINE` | Administrator | System-wide settings |
| `HKEY_CLASSES_ROOT` | Administrator | File associations, COM registration |

## Best Practices for Applications

When designing applications that use the registry:

1. **Prefer user-specific storage**: Use `HKEY_CURRENT_USER` for application settings when possible.
2. **Handle permission failures gracefully**: Your application should continue to function even if registry access fails.
3. **Consider alternatives**: For many scenarios, configuration files or application data folders are better choices than the registry.
4. **Use read-only access when possible**: Open registry keys with the minimum required permissions.

## Security Considerations

- Always validate data before writing to the registry
- Be cautious about what information you store in the registry, as it might be accessible to other applications
- Consider the security implications of storing sensitive information in the registry

## See also

- <xref:Microsoft.Win32.Registry?displayProperty=nameWithType>
- <xref:Microsoft.Win32.RegistryKey?displayProperty=nameWithType>
- [Security and the Registry (Visual Basic)](/dotnet/visual-basic/developing-apps/programming/computer-resources/security-and-the-registry)
29 changes: 29 additions & 0 deletions docs/csharp/programming-guide/file-system/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
---
title: "File system and registry programming"
description: Learn how to work with the file system and Windows Registry in C#, including important considerations about permissions and security.
ms.date: 01/16/2025
helpviewer_keywords:
- "file system [C#]"
- "registry [C#]"
- "permissions [C#]"
- "Windows programming [C#]"
ms.topic: overview
---
# File system and registry programming (C# Programming Guide)

This section covers how to work with the file system and Windows Registry in C# applications, with important considerations about permissions, security, and best practices.

## In this section

- [How to create a key in the registry](how-to-create-a-key-in-the-registry.md) - Learn how to create registry keys and handle permission requirements properly.

## Related sections

- [Microsoft.Win32.Registry Class](../../../fundamentals/runtime-libraries/microsoft-win32-registry.md) - Reference documentation for the Registry class.
- [System.IO Namespace](../../../fundamentals/runtime-libraries/system-io.md) - File system operations and classes.

## See also

- <xref:Microsoft.Win32.Registry?displayProperty=nameWithType>
- <xref:Microsoft.Win32.RegistryKey?displayProperty=nameWithType>
- <xref:System.IO?displayProperty=nameWithType>
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
using Microsoft.Win32;
using System.Runtime.Versioning;

[SupportedOSPlatform("windows")]
class Program
{
static void Main()
{
if (!OperatingSystem.IsWindows())
{
Console.WriteLine("This example requires Windows operating system.");
return;
}

// <CreateRegistryKey>
// Create a registry key under HKEY_CURRENT_USER
// This does not require administrator privileges
RegistryKey userKey = Registry.CurrentUser.CreateSubKey("TestApp");

// Set a value in the registry key
userKey.SetValue("LastRun", DateTime.Now);
userKey.SetValue("UserName", Environment.UserName);

// Close the key
userKey.Close();

Console.WriteLine("Registry key created successfully under HKEY_CURRENT_USER\\TestApp");
// </CreateRegistryKey>

Console.WriteLine("\nPress any key to run the robust example...");
Console.ReadKey();

// <RobustRegistryAccess>
try
{
// Open or create a registry key with error handling
using (RegistryKey robustKey = Registry.CurrentUser.CreateSubKey("TestApp"))
{
if (robustKey != null)
{
// Store application settings
robustKey.SetValue("ConfigVersion", "1.0");
robustKey.SetValue("EnableNotifications", true);
robustKey.SetValue("MaxRetries", 3);

Console.WriteLine("Application settings saved to registry.");

// Read back the values to verify
string? version = robustKey.GetValue("ConfigVersion") as string;
bool notifications = (bool)(robustKey.GetValue("EnableNotifications") ?? false);
int retries = (int)(robustKey.GetValue("MaxRetries") ?? 0);

Console.WriteLine($"Config Version: {version}");
Console.WriteLine($"Notifications Enabled: {notifications}");
Console.WriteLine($"Max Retries: {retries}");
}
else
{
Console.WriteLine("Failed to create or access registry key.");
}
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied. The application doesn't have permission to access this registry key.");
}
catch (System.Security.SecurityException)
{
Console.WriteLine("Security error. The application doesn't have permission to access the registry.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
// </RobustRegistryAccess>

// Demonstrate the difference in permission requirements
Console.WriteLine("\nTrying to access HKEY_LOCAL_MACHINE (may require admin privileges):");
DemonstrateLocalMachineAccess();
}

[SupportedOSPlatform("windows")]
static void DemonstrateLocalMachineAccess()
{
try
{
// This will likely fail without administrator privileges
using (RegistryKey machineKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\TestApp"))
{
if (machineKey != null)
{
machineKey.SetValue("SystemSetting", "value");
Console.WriteLine("Successfully wrote to HKEY_LOCAL_MACHINE");
}
}
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to HKEY_LOCAL_MACHINE. Administrator privileges required.");
}
catch (System.Security.SecurityException)
{
Console.WriteLine("Security error accessing HKEY_LOCAL_MACHINE. Administrator privileges required.");
}
catch (Exception ex)
{
Console.WriteLine($"Error accessing HKEY_LOCAL_MACHINE: {ex.Message}");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
6 changes: 6 additions & 0 deletions docs/csharp/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,12 @@ items:
href: programming-guide/generics/differences-between-cpp-templates-and-csharp-generics.md
- name: Generics in the Run Time
href: programming-guide/generics/generics-in-the-run-time.md
- name: File system and registry
items:
- name: Overview
href: programming-guide/file-system/index.md
- name: "How to create a key in the registry"
href: programming-guide/file-system/how-to-create-a-key-in-the-registry.md
- name: Other C# documentation
items:
- name: C# language reference
Expand Down
Loading