gpt4 book ai didi

c# - 如何使用 Microsoft.Win32.Registry C# 创建注册表项

转载 作者:可可西里 更新时间:2023-11-01 10:25:46 25 4
gpt4 key购买 nike

我想使用 Microsoft.Win32.Registry 直接写入注册表。我可以这样做是一个像这样的 reg 文件:

swreg = File.AppendText(strRegPath); //Opens the file:

swreg.WriteLine(@"[HKEY_CURRENT_USER\Software\Microsoft\Office\Outlook\OMI Account Manager\Accounts\user@domain.com");
swreg.WriteLine("\"DCEmail\"=dword:00000002");
swreg.WriteLine("\"POP3 Server\"=\"10.0.0.200\"");
swreg.WriteLine("\"POP3 Port\"=dword:0000006e");

这会创建一个 reg 文件,我可以执行创建 reg key 的文件。我尝试过使用 Microsoft.Win32.Registry 进行类似操作,如下所示:

var RKOutlook = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\Outlook\OMI Account Manager\Accounts");

if (RKOutlook.OpenSubKey("user@domain.com") == null)
{
RKOutlook.CreateSubKey("user@domain.com");
RKOutlook = RKOutlook.OpenSubKey("user@domain.com", true);
}

但是我收到了 System.NullReferenceException was unhandled 错误。如何在不使用 reg 文件的情况下直接写入注册表?

最佳答案

Reading from and writing to Registry

此代码在 VB.NET 中,但可以转换为 C#以下代码显示如何从 HKEY_CURRENT_USER 中读取字符串。

Microsoft.Win32.RegistryKey regVersion = null;
dynamic keyValue = "Software\\Microsoft\\TestApp\\1.0";
regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyValue, false);
int intVersion = 0;
if (regVersion != null) {
intVersion = regVersion.GetValue("Version", 0);
regVersion.Close();
}

以下代码读取、递增,然后将字符串写入 HKEY_CURRENT_USER。

var regVersion = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0", true);
if (regVersion == null) {
// Key doesn't exist; create it.
regVersion = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\TestApp\\1.0");
}

int intVersion = 0;
if (regVersion != null) {
intVersion = regVersion.GetValue("Version", 0);
intVersion = intVersion + 1;
regVersion.SetValue("Version", intVersion);
regVersion.Close();
}

关于c# - 如何使用 Microsoft.Win32.Registry C# 创建注册表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18962614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com