Read a Registry Key
Asked Answered
J

5

26

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?

Jeanejeanelle answered 4/11, 2009 at 18:53 Comment(0)
R
49

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.
Reagent answered 4/11, 2009 at 19:4 Comment(0)
T
9

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
        }
    }
}
Tetter answered 25/3, 2013 at 20:19 Comment(0)
J
8

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");
        }
    }
}
Jahncke answered 8/5, 2017 at 8:27 Comment(0)
A
2
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;
}
Annmaria answered 4/11, 2009 at 19:12 Comment(0)
F
1

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 .

Ferry answered 5/2, 2013 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.