Odczyt klucza rejestru

Mam aplikację internetową, która importuje biblioteki DLL z folderu bin.

const string dllpath = "Utility.dll";

    [DllImport(dllpath)]

Teraz chcę najpierw zaimportować biblioteki DLL z folderu nie w bieżącym projekcie, ale w innej lokalizacji.

Ścieżka do tego folderu jest przechowywana w kluczu rejestru.

Jak mam to zrobić?

Edit :

Dlaczego nie mogę tego rozgryźć???
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"); nie działa tutaj, ale działa w zdarzeniu pageload...

Ale jeśli to zrobię Import DLL nie będzie działać... Jak mogę to naprawić?
Author: Brad Koch, 2009-11-04

5 answers

Odczyt rejestru jest dość prosty. Przestrzeń nazw Microsoft.Win32 ma statyczną klasę Registry. Aby odczytać klucz z węzła HKLM, kod to:

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

Jeśli węzeł jest HKCU, możesz zastąpić LocalMachine CurrentUser.

Gdy masz obiekt RegistryKey, użyj GetValue, aby pobrać wartość z rejestru. Kontynuując korzystanie z powyższego przykładu, otrzymanie wartości rejestru pathName będzie następujące:

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

I nie zapomnij zamknąć RegistryKey obiektu ,gdy skończysz z nim (lub umieść instrukcję, aby uzyskać wartość w bloku Using).

Aktualizacje

Widzę kilka rzeczy. Najpierw zmieniłbym pathName na statyczną właściwość zdefiniowaną jako:
Private static string PathName
{ 
    get
    {
         using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(@"Software\Copium"))
         {
              return (string)registryKey.GetValue("BinDir");
         }
    }
}

Dwie kwestie były:

  1. odniesienie RegistryKey utrzyma rejestr otwarty. Używanie jej jako zmiennej statycznej w klasie spowoduje problemy na komputerze.
  2. ścieżka rejestru używa ukośników do przodu, a nie do tyłu.
 43
Author: Jeff Siver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-25 22:58:25

Żadna z tych odpowiedzi nie zadziałała. Tego użyłem:

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
        }
    }
}
 8
Author: P.Brian.Mackey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-06 05:54:07

Wszystkie te odpowiedzi mogą prowadzić do problemów z uruchomieniem 64-bitowego systemu operacyjnego - co jest zwykle w dzisiejszych czasach.

W mojej sytuacji kompiluję się do "dowolnego CPU" i oprogramowanie działa dobrze, gdy instaluję się na 64-bitowym systemie operacyjnym. Ale moje testy jednostkowe napotykają problemy-oczywiście są one wykonywane w trybie 32bit.

W tym przypadku nie HKEY_LOCAL_MACHINE\SOFTWARE\MyCompany\MySoftware jest wyszukiwany, ale HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MyCompany\MySoftware ale nie ma wpisów!

W tej sytuacji musimy określić punkt początkowy poszukiwań za pomocą

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

W sumie możemy użyć.

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");
        }
    }
}
 4
Author: sahl04,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-08 08:27:24
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;
}
 2
Author: Zinx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-06 05:54:44

Możesz użyć tego:

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

Aby uzyskać więcej informacji odwiedź tę stronę internetową .

 1
Author: Mahmut EFE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-06 05:56:06