2009-11-04 20 views
20

Tengo una aplicación web que importa archivos DLL de la carpeta bin.Lea una clave de registro

const string dllpath = "Utility.dll"; 

    [DllImport(dllpath)] 

Ahora lo que quiero hacer es la primera importación de los archivos DLL de una carpeta no en el proyecto actual, pero en algún lugar diferente.

La ruta de esa carpeta se almacena en una clave de registro.

¿Cómo debo hacer esto?

Editar:

Por qué no puedo resolver esto ???

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"); no funciona aquí, pero está trabajando en el caso pageload ...

pero si lo hago esta importación DLL no va a funcionar ... ¿Cómo puedo solucionar este problema?

Respuesta

43

Leer el registro es bastante sencillo. El espacio de nombres Microsoft.Win32 tiene una clase estática Registry. Para leer una clave del nodo HKLM, el código es:

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

Si el nodo es HKCU, puede reemplazar LocalMachine con CurrentUser.

Una vez que tenga el objeto RegistryKey, use GetValue para obtener el valor del registro. Continuando con el ejemplo anterior, para obtener el valor del registro de ruta sería:

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

Y no se olvide de cerrar el objeto RegistryKey cuando haya terminado con él (o poner la declaración para obtener el valor en un bloque Using)

Actualizaciones

veo un par de cosas. En primer lugar, me gustaría cambiar el camino completo hasta ser una propiedad estática define como:

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

Los dos temas fueron:

  1. La referencia RegistryKey mantendrá el registro abierto. Usar eso como una variable estática en la clase causará problemas en la computadora.
  2. Las barras diagonales de uso del trazado del registro, no las barras posteriores.
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; 
} 
1

Puede utilizar esta:

/// <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; 
     } 
    } 
} 

Para obtener más información, visite this web site.

8

Ninguna de estas respuestas funcionó para mí.Esto es lo que utilicé:

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 
     } 
    } 
} 
2

Todas estas respuestas pueden ocasionar problemas al ejecutar el sistema operativo de 64 bits, lo que es habitual hoy en día.

En mi situación, compilo al objetivo 'Cualquier CPU' y el software funciona bien cuando instalo en sistema operativo de 64 bits. Pero mis pruebas unitarias están teniendo problemas, obviamente se ejecutan en modo de 32 bits.

En este caso no se busca HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany\MySoftware pero HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MyCompany\MySoftware pero no hay entradas!

En esta situación tenemos que especificar el punto de inicio de nuestra búsqueda usando

RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) 

En total podemos utilizar.

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"); 
     } 
    } 
} 
Cuestiones relacionadas