Csharp/C Sharp/Development Class/Registry

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Accessing the Registry

using System;
using Microsoft.Win32;
class MainClass {
    public static void Main(String[] args) {
        RegistryKey rk = Registry.LocalMachine;
        RegistryKey subKey =rk.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\\");
        object VendorID = subKey.GetValue("VendorIdentifier");
        Console.WriteLine(VendorID);
        RegistryKey randkey = Registry.CurrentUser;
        string key = "";
        for (int i = 0; i < args.Length - 1; ++i) {
            key += args[i];
            key += "\\";
        }
        RegistryKey subKey1 = randkey.OpenSubKey(key);
        object keyValue = subKey1.GetValue(args[args.Length - 1]);
        Console.WriteLine("Key {0} Value {1} = {2}",key,args[args.Length - 1],keyValue);
        RegistryKey companyKey = Registry.CurrentUser;
        RegistryKey subKey3 = companyKey.CreateSubKey("MyCompany");
        subKey3.SetValue("Name", "MyCompany");
        subKey3.SetValue("RegistrationID", 1234567);
        subKey3.SetValue("Date", "01/01/2001");
        companyKey.Close();
        RegistryKey companyKeyRead = Registry.CurrentUser;
        RegistryKey subKey4 = companyKeyRead.OpenSubKey("MyCompany");
        object companyName = subKey4.GetValue("MyCompany");
        Console.WriteLine("Company Name: {0}", companyName);
        object regID = subKey4.GetValue("RegistrationID");
        Console.WriteLine("RegistrationID: {0}", regID);
        object theDate = subKey4.GetValue("Date");
        Console.WriteLine("Date: {0}", theDate);
    }
}


Enumerating Registry Keys

using System;
using Microsoft.Win32;
class Class1 {
    static void Main(string[] args) {
        RegistryKey myRegKey = Registry.LocalMachine;
        myRegKey = myRegKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
        String[] subkeyNames = myRegKey.GetSubKeyNames();
        foreach (String s in subkeyNames) {
            RegistryKey UninstallKey = Registry.LocalMachine;
            UninstallKey = UninstallKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + s);
            try {
                Object oValue = UninstallKey.GetValue("DisplayName");
                Console.WriteLine(oValue.ToString());
            } catch (NullReferenceException) {
            }
        }
    }
}


Get Registry value

/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using Microsoft.Win32;
public class CardGrab
{
    public static void Main()
    {
    RegistryKey start = Registry.LocalMachine;
    RegistryKey cardServiceName, networkKey;
    string networkcardKey = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards";
    string serviceKey = "SYSTEM\\CurrentControlSet\\Services\\";
    string networkcardKeyName, deviceName, deviceServiceName, serviceName;
    RegistryKey serviceNames = start.OpenSubKey(networkcardKey);
    if (serviceNames == null)
    {
        Console.WriteLine("Bad registry key");
        return;
    }
    string[] networkCards = serviceNames.GetSubKeyNames();
    serviceNames.Close();
    foreach(string keyName in networkCards)
    {
        networkcardKeyName = networkcardKey + "\\" + keyName;
        cardServiceName = start.OpenSubKey(networkcardKeyName);
        if (cardServiceName == null)
        {
        Console.WriteLine("Bad registry key: {0}", networkcardKeyName);
        return;
        }
        deviceServiceName = (string)cardServiceName.GetValue("ServiceName");
        deviceName = (string)cardServiceName.GetValue("Description");
        Console.WriteLine("\nNetwork card: {0}", deviceName);
        
        serviceName = serviceKey + deviceServiceName +
             "\\Parameters\\Tcpip";
        networkKey = start.OpenSubKey(serviceName);
        if (networkKey == null)
        {
        Console.WriteLine("    No IP configuration set");
        } else
        {
        string[] ipaddresses = (string[])networkKey.GetValue("IPAddress");
        string[] defaultGateways = (string[])networkKey.GetValue("DefaultGateway");
        string[] subnetmasks = (string[])networkKey.GetValue("SubnetMask");
        foreach(string ipaddress in ipaddresses)
        {
            Console.WriteLine("    IP Address: {0}", ipaddress);
        }
        foreach(string subnetmask in subnetmasks)
        {
            Console.WriteLine("    Subnet Mask: {0}", subnetmask);
        }
        foreach(string defaultGateway in defaultGateways)
        {
            Console.WriteLine("    Gateway: {0}", defaultGateway);
        }
        networkKey.Close();
        }
    }
    start.Close();
    }
}


Get the Registry key found for CurrentUser

using System;
using Microsoft.Win32;

class MainClass {
    public static void SearchSubKeys(RegistryKey root, String searchKey) {
        foreach (string keyname in root.GetSubKeyNames()) {
            try {
                using (RegistryKey key = root.OpenSubKey(keyname)) {
                    if (keyname == searchKey) PrintKeyValues(key);
                    SearchSubKeys(key, searchKey);
                }
            } catch (System.Security.SecurityException) {
            }
        }
    }
    public static void PrintKeyValues(RegistryKey key) {
        Console.WriteLine("Registry key found : {0} contains {1} values",
            key.Name, key.ValueCount);
        foreach (string valuename in key.GetValueNames()) {
            if (key.GetValue(valuename) is String) {
                Console.WriteLine(" Value : {0} = {1}",
                    valuename, key.GetValue(valuename));
            }
        }
    }
    public static void Main(String[] args) {
        if (args.Length > 0) {
            using (RegistryKey root = Registry.CurrentUser) {
                SearchSubKeys(root, args[0]);
            }
        }
    }
}


Open a SubKey in Registry

using System;
using Microsoft.Win32;

class MainClass {
    public static void SearchSubKeys(RegistryKey root, String searchKey) {
        foreach (string keyname in root.GetSubKeyNames()) {
            try {
                using (RegistryKey key = root.OpenSubKey(keyname)) {
                    if (keyname == searchKey) PrintKeyValues(key);
                    SearchSubKeys(key, searchKey);
                }
            } catch (System.Security.SecurityException) {
            }
        }
    }
    public static void PrintKeyValues(RegistryKey key) {
        Console.WriteLine("Registry key found : {0} contains {1} values",
            key.Name, key.ValueCount);
        foreach (string valuename in key.GetValueNames()) {
            if (key.GetValue(valuename) is String) {
                Console.WriteLine(" Value : {0} = {1}",
                    valuename, key.GetValue(valuename));
            }
        }
    }
    public static void Main(String[] args) {
        if (args.Length > 0) {
            using (RegistryKey root = Registry.CurrentUser) {
                SearchSubKeys(root, args[0]);
            }
        }
    }
}


Registry.LocalMachine

using System;
using Microsoft.Win32;
using System.Security.Permissions;
[RegistryPermissionAttribute(SecurityAction.Demand)]
class Class1 {
    static void Main(string[] args) {
        RegistryKey myRegKey = Registry.LocalMachine;
        myRegKey = myRegKey.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
        Object oValue = myRegKey.GetValue("RegisteredOwner");
        Console.WriteLine("OS Registered Owner: {0}", oValue.ToString());
    }
}


Retrieve the CPU Type and Speed from the Registry

using System;
using Microsoft.Win32;
class Class1 {
    static void Main(string[] args) {
        RegistryKey RegKey = Registry.LocalMachine;
        RegKey = RegKey.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
        Object cpuSpeed = RegKey.GetValue("~MHz");
        Object cpuType = RegKey.GetValue("VendorIdentifier");
        Console.WriteLine("You have a {0} running at {1} MHz.", cpuType, cpuSpeed);
    }
}


Use GetValue and SetValue to get and save value to Registry

using System;
using Microsoft.Win32;
class MainClass {
    public static void Main(String[] args) {
        string lastUser;
        string lastRun;
        int runCount;
        lastUser = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\A\C#","", "Nobody");
        if (lastUser == null) {
            lastUser = "Nobody";
            lastRun = "Never";
            runCount = 0;
        } else {
            lastRun = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\A\C#","LastRun", "Never");            runCount = (Int32)Registry.GetValue(
                @"HKEY_CURRENT_USER\Software\A\C#","RunCount", 0);
        }
        Console.WriteLine("Last user name: " + lastUser);
        Console.WriteLine("Last run date/time: " + lastRun);
        Console.WriteLine("Previous executions: " + runCount);
        Registry.SetValue(@"HKEY_CURRENT_USER\Software\A\C#","", Environment.UserName, RegistryValueKind.String);
        Registry.SetValue(@"HKEY_CURRENT_USER\Software\A\C#","LastRun", DateTime.Now.ToString(), RegistryValueKind.String);
        Registry.SetValue(@"HKEY_CURRENT_USER\Software\A\C#","RunCount", ++runCount, RegistryValueKind.DWord);
    }
}


Write a Text and DWord Value to the Registry

using System;
using Microsoft.Win32;
class Class1 {
    static void Main(string[] args) {
        RegistryKey RegKeyWrite = Registry.CurrentUser;
        RegKeyWrite = RegKeyWrite.CreateSubKey("Software\\CSHARP\\WriteRegistryValue");
        RegKeyWrite.SetValue("Success", "TRUE");
        RegKeyWrite.SetValue("AttemptNumber", 1);
        RegKeyWrite.Close();
        RegistryKey RegKeyRead = Registry.CurrentUser;
        RegKeyRead = RegKeyRead.OpenSubKey("Software\\CSHARP\\WriteRegistryValue");
        Object regSuccessful = RegKeyRead.GetValue("Success");
        Object regAttemptNumber = RegKeyRead.GetValue("AttemptNumber");
        RegKeyRead.Close();
        Console.WriteLine(regSuccessful);
      
    }
}