首页 > 解决方案 > 如何从 C# 读取注册表数据

问题描述

在我的 c# 程序中,我正在运行一个 python 进程。目前我正在为 python.exe 使用硬编码路径,但我想使用 Windows 注册表将路径返回给我。

我在以下 Windows 注册表中找到了 python 路径信息: HKEY_CURRENT_USER\Software\Python\PythonCore\3.7-32\InstallPath

通过一些谷歌搜索,我找到了以下解决方案: https ://stackoverflow.com/a/18234755/7183609

但是当我运行我的代码时,变量key总是为空

try
{
    using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Python\\PythonCore\\3.7-32\\InstallPath"))
    {
        if (key != null)
        {
            // do things
        }
    }
}
catch (Exception ex)
{
    // do other things
}

我做错了什么,我需要添加一些东西来使它工作吗?

标签: c#registry

解决方案


John Wu 指出 LocalMachine 是错误的。

改变了

using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"HKEY_CURRENT_USER\Software\Python\PythonCore\3.7-32\InstallPath"))

using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"HKEY_CURRENT_USER\Software\Python\PythonCore\3.7-32\InstallPath"))

推荐阅读