views:

515

answers:

3

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?

Thanks

why cant 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"); not working here but working in pageload event...

but if i do this DLL import wont work... how can i fix this

A: 

Take a look at the Registry.OpenSubKey method.

Chris Pebble
+5  A: 

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

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.
Jeff Siver
Not sure if this is true in the latest and greatest, but I just tried this in Studio 2005/.NET 2.0, and had to use back slashes in the syntax @"Software\Copiun". Using forward slashes returned a null RegistryKey.
Chuck Wilbur
+1  A: 
        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;
        }
Zinx