C#写注册表
时间: 2023-07-12 11:10:23 浏览: 90
要在C#中写入注册表,可以使用Microsoft.Win32命名空间中的Registry类。下面是一个简单的示例,演示如何将一个值写入注册表中的键:
```csharp
using Microsoft.Win32;
// 创建或打开名为“MyKey”的注册表键
RegistryKey key = Registry.CurrentUser.CreateSubKey("MyKey");
// 将名为“MyValue”的字符串值写入“MyKey”键
key.SetValue("MyValue", "Hello, World!");
// 关闭键
key.Close();
```
以上代码将在当前用户的注册表中创建或打开名为“MyKey”的键,并将名为“MyValue”的字符串值设置为“Hello, World!”。请注意,这将在HKEY_CURRENT_USER\MyKey路径下创建一个名为“MyValue”的新值。
当然,还有很多其他的Registry类方法和属性,可以用于读取、修改和删除注册表中的键和值。
相关问题
c#操作注册表
在C#中,可以使用Microsoft.Win32命名空间下的Registry类来操作Windows注册表。下面是一些常见的注册表操作示例:
1. 读取注册表键值:
```csharp
using Microsoft.Win32;
// 读取HKEY_CURRENT_USER下的Software\\Microsoft\\Windows\\CurrentVersion\\Run键值
string runPath = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run").GetValue("MyApp") as string;
```
2. 写入注册表键值:
```csharp
using Microsoft.Win32;
// 写入HKEY_CURRENT_USER下的Software\\Microsoft\\Windows\\CurrentVersion\\Run键值
Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true).SetValue("MyApp", "C:\\MyApp\\MyApp.exe");
```
3. 删除注册表键值:
```csharp
using Microsoft.Win32;
// 删除HKEY_CURRENT_USER下的Software\\Microsoft\\Windows\\CurrentVersion\\Run键值
Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true).DeleteValue("MyApp");
```
以上是一些基本的注册表操作示例,你可以根据自己的需求进行相应的操作。需要注意的是,操作注册表需要管理员权限。
c# 获取注册表 键值
你可以使用 C# 中的 Microsoft.Win32 命名空间来获取注册表中的键值。以下是一个简单的示例代码:
```csharp
using Microsoft.Win32;
// 获取 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion 中的 ProductName 键值
RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion");
string productName = key.GetValue("ProductName").ToString();
Console.WriteLine("ProductName: " + productName);
```
在上面的示例代码中,我们使用了 Registry.CurrentUser.OpenSubKey 方法打开了 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion 键,并使用了 GetValue 方法获取了其中的 ProductName 键值。你可以根据需要修改键名和路径。