Tải bản đầy đủ - 0 (trang)
14-4. Read and Write to the Windows Registry

14-4. Read and Write to the Windows Registry

Tải bản đầy đủ - 0trang

CHAPTER 14 ■ WINDOWS INTEGRATION







A string containing the name of the value in the key you want to read.







An object containing the default value to return if the named value is not present

in the key.



GetValue returns an object containing either the data read from the registry or the default value

specified as the third argument if the named value is not found. If the specified key does not exist,

GetValue returns null.

SetValue offers two overloads. The most functional expects the following arguments:





A string containing the fully qualified name of the key you want to write. The key

must start with one of the root key names specified previously.







A string containing the name of the value in the key you want to write.







An object containing the value to write.







An element of the Microsoft.Win32.RegistyValueKind enumeration that specifies

the registry data type that should be used to hold the data.



If the registry key specified in the SetValue call does not exist, it is automatically created.



The Code

The following example demonstrates how to use GetValue and SetValue to read from and write to the

registry. Every time the example is run, it reads usage information from the registry and displays it to the

screen. The example also updates the stored usage information, which you can see the next time you run

the example.

using System;

using Microsoft.Win32;

namespace Apress.VisualCSharpRecipes.Chapter14

{

class Recipe14_04

{

public static void Main(String[] args)

{

// Variables to hold usage information read from registry.

string lastUser;

string lastRun;

int runCount;

// Read the name of the last user to run the application from the

// registry. This is stored as the default value of the key and is

// accessed by not specifying a value name. Cast the returned Object

// to a string.

lastUser = (string)Registry.GetValue(

@"HKEY_CURRENT_USER\Software\Apress\Visual C# Recipes",

"", "Nobody");



693



www.it-ebooks.info



CHAPTER 14 ■ WINDOWS INTEGRATION



// If lastUser is null, it means that the specified registry key

// does not exist.

if (lastUser == null)

{

// Set initial values for the usage information.

lastUser = "Nobody";

lastRun = "Never";

runCount = 0;

}

else

{

// Read the last run date and specify a default value of

// "Never". Cast the returned Object to string.

lastRun = (string)Registry.GetValue(

@"HKEY_CURRENT_USER\Software\Apress\Visual C# Recipes",

"LastRun", "Never");

// Read the run count value and specify a default value of

// 0 (zero). Cast the Object to Int32 and assign to an int.

runCount = (Int32)Registry.GetValue(

@"HKEY_CURRENT_USER\Software\Apress\Visual C# Recipes",

"RunCount", 0);

}

// Display the usage information.

Console.WriteLine("Last user name: " + lastUser);

Console.WriteLine("Last run date/time: " + lastRun);

Console.WriteLine("Previous executions: " + runCount);

// Update the usage information. It doesn't matter if the registry

// key exists or not, SetValue will automatically create it.

// Update the "last user" information with the current username.

// Specify that this should be stored as the default value

// for the key by using an empty string as the value name.

Registry.SetValue(

@"HKEY_CURRENT_USER\Software\Apress\Visual C# Recipes",

"", Environment.UserName, RegistryValueKind.String);

// Update the "last run" information with the current date and time.

// Specify that this should be stored as a string value in the

// registry.

Registry.SetValue(

@"HKEY_CURRENT_USER\Software\Apress\Visual C# Recipes",

"LastRun", DateTime.Now.ToString(), RegistryValueKind.String);

// Update the usage count information. Specify that this should

// be stored as an integer value in the registry.

Registry.SetValue(

@"HKEY_CURRENT_USER\Software\Apress\Visual C# Recipes",

"RunCount", ++runCount, RegistryValueKind.DWord);



694



www.it-ebooks.info



CHAPTER 14 ■ WINDOWS INTEGRATION



// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



14-5. Search the Windows Registry

Problem

You need to search the Windows registry for a key that contains a specific value or content.



Solution

Use the Microsoft.Win32.Registry class to obtain a Microsoft.Win32.RegistryKey object that represents the

root key of a registry hive you want to search. Use the members of this RegistryKey object to navigate through

and enumerate the registry key hierarchy, as well as to read the names and content of values held in the keys.



How It Works

You must first obtain a RegistryKey object that represents a base-level key and navigate through the

hierarchy of RegistryKey objects as required. The Registry class implements a set of seven static fields

that return RegistryKey objects representing base-level registry keys; Table 14-3 describes the registry

location to where each of these fields maps.

Table 14-3. Static Fields of the Registry Class



Field



Registry Mapping



ClassesRoot



HKEY_CLASSES_ROOT



CurrentConfig



HKEY_CURRENT_CONFIG



CurrentUser



HKEY_CURRENT_USER



DynData



HKEY_DYN_DATA



LocalMachine



HKEY_LOCAL_MACHINE



PerformanceData



HKEY_PERFORMANCE_DATA



Users



HKEY_USERS



695



www.it-ebooks.info



CHAPTER 14 ■ WINDOWS INTEGRATION



■ Tip The static method RegistryKey.OpenRemoteBaseKey allows you to open a registry base key on a remote

machine. See the .NET Framework SDK documentation for details of its use.



Once you have the base-level RegistryKey object, you must navigate through its child subkeys

recursively. To support navigation, the RegistryKey class allows you to do the following:





Get the number of immediate subkeys using the SubKeyCount property.







Get a string array containing the names of all subkeys using the GetSubKeyNames

method.







Get a RegistryKey reference to a subkey using the OpenSubKey method. The

OpenSubKey method provides two overloads: the first opens the named key as readonly; the second accepts a bool argument that, if true, will open a writable

RegistryKey object.



Once you obtain a RegistryKey, you can create, read, update, and delete subkeys and values using

the methods listed in Table 14-4. Methods that modify the contents of the key require you to have a

writable RegistryKey object.

Table 14-4. RegistryKey Methods to Create, Read, Update, and Delete Registry Keys and Values



Method



Description



CreateSubKey



Creates a new subkey with the specified name and returns a writable RegistryKey

object. If the specified subkey already exists, CreateSubKey will return a writable

reference to the existing subkey.



DeleteSubKey



Deletes the subkey with the specified name, which must be empty of subkeys (but

not values); otherwise, a System.InvalidOperationException is thrown.



DeleteSubKeyTree



Deletes the subkey with the specified name along with all of its subkeys.



DeleteValue



Deletes the value with the specified name from the current key.



GetValue



Returns the value with the specified name from the current key. The value is

returned as an object, which you must cast to the appropriate type. The simplest

form of GetValue returns null if the specified value doesn’t exist. An overload allows

you to specify a default value to return (instead of null) if the named value doesn’t

exist.



GetValueKind



Returns the registry data type of the value with the specified name in the current

key. The value is returned as a member of the Microsoft.Win32.RegistryValueKind

enumeration.



696



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

14-4. Read and Write to the Windows Registry

Tải bản đầy đủ ngay(0 tr)

×