2009-11-04 13 views
20

Ho un'applicazione Web che sta importando DLL dalla cartella bin.Leggere una chiave di registro

const string dllpath = "Utility.dll"; 

    [DllImport(dllpath)] 

Ora quello che voglio fare è prima di importazione le DLL da una cartella non nel progetto corrente ma ad un certo posizione diversa.

Il percorso di tale cartella è memorizzato in una chiave di registro.

Come devo fare?

Edit:

Perché non è possibile lavorare questo fuori ???

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"); non funziona qui, ma sta lavorando in caso pageload ...

Ma se faccio questa DLL importazione non funzionerà ... Come posso risolvere questo problema?

risposta

43

Leggere il registro è piuttosto semplice. Lo spazio dei nomi Microsoft.Win32 ha una classe statica Registry. Per leggere una chiave dal nodo HKLM, il codice è:

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

Se il nodo è HKCU, è possibile sostituire con LocalMachineCurrentUser.

Una volta ottenuto l'oggetto RegistryKey, utilizzare GetValue per ottenere il valore dal registro. Continuando Utilizzando l'esempio precedente, ottenendo il valore del Registro pathName sarebbe:

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

E non dimenticare di chiudere l'oggetto RegistryKey quando si è fatto con esso (o mettere la dichiarazione per ottenere il valore in un blocco Using).

Aggiornamenti

vedo un paio di cose. In primo luogo, vorrei cambiare pathName da una proprietà statica definito come:

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

Le due questioni sono state:

  1. Il riferimento RegistryKey manterrà il Registro di sistema aperto. Usarlo come variabile statica nella classe causerà problemi sul computer.
  2. Il percorso del Registro di sistema utilizza le barre in avanti, non le barre indietro.
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

È possibile utilizzare questo:

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

Per ulteriori informazioni visitare this web site.

8

Nessuna di queste risposte ha funzionato per me.Questo è quello che ho usato:

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

Tutte queste risposte possono portare a problemi di sistema operativo a 64 bit, cosa normale al giorno d'oggi.

Nella mia situazione, compilo a destinazione "Qualsiasi CPU" e il software funziona correttamente quando installo su sistema operativo a 64 bit. Ma i miei test di unità stanno incontrando problemi - ovviamente sono eseguiti in modalità 32 bit.

In questo caso non viene cercata la HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany\MySoftware ma HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MyCompany\MySoftware ma non ci sono voci!

In questa situazione dobbiamo specificare il punto iniziale della nostra ricerca con

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

In totale possiamo usare.

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"); 
     } 
    } 
} 
Problemi correlati