C# 读取注册表项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1675864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:54:06  来源:igfitidea点击:

Read a Registry Key

c#asp.netvisual-studioregistrydllimport

提问by user175084

I have a web application which is importing DLLs from the bin folder.

我有一个 Web 应用程序,它从 bin 文件夹中导入 DLL。

const string dllpath = "Utility.dll";

    [DllImport(dllpath)]

Now what I want to do is first import the DLLs from a folder not in the current project but at some different location.

现在我想要做的是首先从不在当前项目中而是在某个不同位置的文件夹中导入 DLL。

The path of that folder is stored in a registry key.

该文件夹的路径存储在注册表项中。

How should I do this?

我该怎么做?

Edit:

编辑

Why can't I work this out???

为什么我不能解决这个问题???

public partial class Reports1 : System.Web.UI.Page
{

    RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\xyz");
    string pathName = (string)registryKey.GetValue("BinDir");

    const string dllpath = pathName;
    [DllImport(dllpath)]
    public static extern bool GetErrorString(uint lookupCode, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder buf, uint bufSize);

    protected void Page_Load(object sender, EventArgs e)
    {

string pathName = (string)registryKey.GetValue("BinDir");is not working here, but is working in the pageload event...

string pathName = (string)registryKey.GetValue("BinDir");不在此处工作,但在页面加载事件中工作...

But if I do this DLL import won't work... How can I fix this?

但是,如果我执行此 DLL 导入将不起作用...我该如何解决这个问题?

采纳答案by Jeff Siver

Reading the registry is pretty straightforward. The Microsoft.Win32namespace has a Registrystatic class. To read a key from the HKLMnode, the code is:

读取注册表非常简单。该Microsoft.Win32命名空间有一个Registry静态类。要从HKLM节点读取密钥,代码为:

RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\NodeName")

If the node is HKCU, you can replace LocalMachinewith CurrentUser.

如果节点是HKCU,则可以替换LocalMachineCurrentUser

Once you have the RegistryKeyobject, use GetValueto get the value from the registry. Continuing Using the example above, getting the pathName registry value would be:

一旦你的RegistryKey对象,使用GetValue来从注册表中的值。继续使用上面的示例,获取 pathName 注册表值将是:

string pathName = (string) registryKey.GetValue("pathName");

And don't forget to close the RegistryKeyobject when you are done with it (or put the statement to get the value into a Usingblock).

并且不要忘记在完成后关闭RegistryKey对象(或将语句放入Using块中以获取值)。

Updates

更新

I see a couple of things. First, I would change pathName to be a static property defined as:

我看到了一些事情。首先,我将 pathName 更改为定义为的静态属性:

Private static string PathName
{ 
    get
    {
         using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Copium"))
         {
              return (string)registryKey.GetValue("BinDir");
         }
    }
}

The two issues were:

这两个问题是:

  1. The RegistryKeyreference will keep the registry open. Using that as a static variable in the class will cause issues on the computer.
  2. Registry path's use forward slashes, not back slashes.
  1. RegistryKey引用将使注册表保持打开状态。将其用作类中的静态变量会导致计算机出现问题。
  2. 注册表路径使用正斜杠,而不是反斜杠。

回答by Zinx

try
{
    RegistryKey regKey = Registry.LocalMachine;
    regKey = regKey.OpenSubKey(@"Software\Application\");

    if (regKey != null)
    {
        return regKey.GetValue("KEY NAME").ToString();
    }
    else
    {
        return null;
    }
}
catch (Exception ex)
{
  return null;
}

回答by Mahmut EFE

You can use this:

你可以使用这个:

/// <summary>
/// To read a registry key.
/// input: KeyName (string)
/// output: value (string) 
/// </summary>
public string Read(string KeyName)
{
    // Opening the registry key
    RegistryKey rk = baseRegistryKey ;
    // Open a subKey as read-only
    RegistryKey sk1 = rk.OpenSubKey(subKey);
    // If the RegistrySubKey doesn't exist -> (null)
    if ( sk1 == null )
    {
        return null;
    }
    else
    {
        try 
        {
            // If the RegistryKey exists I get its value
            // or null is returned.
            return (string)sk1.GetValue(KeyName.ToUpper());
        }
        catch (Exception e)
        {
            // AAAAAAAAAAARGH, an error!
            ShowErrorMessage(e, "Reading registry " + KeyName.ToUpper());
            return null;
        }
    }
}

For more information visit this web site .

如需更多信息,请访问此网站

回答by P.Brian.Mackey

None of these answers worked for me. This is what I used:

这些答案都不适合我。这是我使用的:

static void Main()
{
    const string dotNetFourPath = "Software\Microsoft";//note backslash
    using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(dotNetFourPath))
    {
        Console.WriteLine(registryKey.SubKeyCount);//registry is not null
        foreach (var VARIABLE in registryKey.GetSubKeyNames())
        {
            Console.WriteLine(VARIABLE);//here I can see I have many keys
            //no need to switch to x64 as suggested on other posts
        }
    }
}

回答by sahl04

All these answers may lead to problems running on 64bit OS - which is usual nowadays.

所有这些答案都可能导致在 64 位操作系统上运行时出现问题 - 这在当今很常见。

In my situation, i compile to 'Any CPU' target and the software is working fine when i install on 64bit OS. But my unit tests are running into problems - obviously they are executed in 32bit mode.

在我的情况下,我编译为“任何 CPU”目标,并且当我安装在 64 位操作系统上时,软件运行良好。但是我的单元测试遇到了问题——显然它们是在 32 位模式下执行的。

In this case not the HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany\MySoftwareis searched but HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MyCompany\MySoftwarebut there are no entries!

在这种情况下,不是HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany\MySoftware搜索,HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MyCompany\MySoftware而是没有条目!

In this situation we have to specify the start point of our search using

在这种情况下,我们必须使用指定搜索的起点

RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)

In total we can use.

我们总共可以使用。

string configurationDirectory = string.Empty;

using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
    using (RegistryKey registryKey = hklm.OpenSubKey(@"SOFTWARE\MyCompany\MySoftware"))
    {
        if (registryKey != null)
        {
            configurationDirectory = (string)registryKey.GetValue("ConfigurationDirectory");
        }
    }
}