Read a Registry Key

2019-01-13 21:38发布

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

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.

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...

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

5条回答
地球回转人心会变
2楼-- · 2019-01-13 21:51

Reading the registry is pretty straightforward. The Microsoft.Win32 namespace has a Registry static class. To read a key from the HKLM node, the code is:

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

If the node is HKCU, you can replace LocalMachine with CurrentUser.

Once you have the RegistryKey object, use GetValue to get the value from the registry. Continuing Using the example above, getting the pathName registry value would be:

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

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

Updates

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

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

The two issues were:

  1. The RegistryKey reference 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.
查看更多
唯我独甜
3楼-- · 2019-01-13 21:55

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

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.

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

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");
        }
    }
}
查看更多
够拽才男人
4楼-- · 2019-01-13 22:07
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;
}
查看更多
欢心
5楼-- · 2019-01-13 22:09

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
        }
    }
}
查看更多
Explosion°爆炸
6楼-- · 2019-01-13 22:13

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 .

查看更多
登录 后发表回答