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?
Reading the registry is pretty straightforward. The
Microsoft.Win32
namespace has aRegistry
static class. To read a key from theHKLM
node, the code is:If the node is
HKCU
, you can replaceLocalMachine
withCurrentUser
.Once you have the
RegistryKey
object, useGetValue
to get the value from the registry. Continuing Using the example above, getting the pathName registry value would be:And don't forget to close the
RegistryKey
object when you are done with it (or put the statement to get the value into aUsing
block).Updates
I see a couple of things. First, I would change pathName to be a static property defined as:
The two issues were:
RegistryKey
reference will keep the registry open. Using that as a static variable in the class will cause issues on the computer.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 butHKEY_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
In total we can use.
None of these answers worked for me. This is what I used:
You can use this:
For more information visit this web site .