Read a Registry Key

user175084 picture user175084 · Nov 4, 2009 · Viewed 78.2k times · Source

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?

Answer

Jeff Siver picture Jeff Siver · Nov 4, 2009

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.