Tải bản đầy đủ - 0 (trang)
14-5. Search the Windows Registry

14-5. Search the Windows Registry

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

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



CHAPTER 14 ■ WINDOWS INTEGRATION



Method



Description



GetValueNames



Returns a string array containing the names of all values in the current registry key.



SetValue



Creates (or updates) the value with the specified name. In 2.0, you can specify the

data type used to store the value with the overload that takes a RegistryValueKind as

last parameter. If you don’t provide such a value kind, one will be calculated

automatically, based on the managed type of the object you pass as value to set.



■ Tip On 64-bit versions of Windows, separate portions of the registry exist for 32-bit and 64-bit applications. The

RegistryView enumeration can be used as an argument to the static OpenBaseKey method of RegistryKey to

specify which portion of the registry is accessed. See the .NET Framework SDK documentation for further details.



The RegistryKey class implements IDisposable; you should call the IDisposable.Dispose method to

free operating system resources when you have finished with the RegistryKey object.



The Code

The following example takes a single command-line argument and recursively searches the CurrentUser

hive of the registry looking for keys with names matching the supplied argument. When the example

finds a match, it displays all string type values contained in the key to the console.

using System;

using Microsoft.Win32;

namespace Apress.VisualCSharpRecipes.Chapter14

{

class Recipe14_05

{

public static void SearchSubKeys(RegistryKey root, String searchKey)

{

try

{

// Get the subkeys contained in the current key.

string[] subkeys = root.GetSubKeyNames();

// Loop through all subkeys contained in the current key.

foreach (string keyname in subkeys)

{

try

{

using (RegistryKey key = root.OpenSubKey(keyname))

{



697



www.it-ebooks.info



CHAPTER 14 ■ WINDOWS INTEGRATION



if (keyname == searchKey) PrintKeyValues(key);

SearchSubKeys(key, searchKey);

}

}

catch (System.Security.SecurityException)

{

// Ignore SecurityException for the purpose of the example.

// Some subkeys of HKEY_CURRENT_USER are secured and will

// throw a SecurityException when opened.

}

}

}

catch (UnauthorizedAccessException)

{

// Ignore UnauthorizedAccessException for the purpose of the example

// - this exception is thrown if the user does not have the

// rights to read part of the registry.

}

}

public static void PrintKeyValues(RegistryKey key)

{

// Display the name of the matching subkey and the number of

// values it contains.

Console.WriteLine("Registry key found : {0} contains {1} values",

key.Name, key.ValueCount);

// Loop through the values and display.

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)

{

// Open the CurrentUser base key.

using (RegistryKey root = Registry.CurrentUser)

{

// Search recursively through the registry for any keys

// with the specified name.

SearchSubKeys(root, args[0]);

}

}



698



www.it-ebooks.info



CHAPTER 14 ■ WINDOWS INTEGRATION



// Wait to continue.

Console.WriteLine(Environment.NewLine);

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

Console.ReadLine();

}

}

}



Usage

Running the example using the command Recipe14-05 Environment will display output similar to the

following when executed using the command on a machine running Windows 7:

Registry key found : HKEY_CURRENT_USER\Environment contains 2 values

Value : TEMP = C:\Users\Adam\AppData\Local\Temp

Value : TMP = C:\Users\Adam\AppData\Local\Temp



14-6. Create a Windows Service

Problem

You need to create an application that will run as a Windows service.



Solution

Create a class that extends System.ServiceProcess.ServiceBase. Use the inherited properties to control

the behavior of your service, and override inherited methods to implement the functionality required.

Implement a Main method that creates an instance of your service class and passes it to the static

ServiceBase.Run method.



■ Note The ServiceBase class is defined in the System.Serviceprocess.dll assembly, so you must include a

reference to this assembly when you build your service class.



How It Works

To create a Windows service manually, you must implement a class derived from the ServiceBase class.

The ServiceBase class provides the base functionality that allows the Windows Service Control Manager



699



www.it-ebooks.info



CHAPTER 14 ■ WINDOWS INTEGRATION



(SCM) to configure the service, operate the service as a background task, and control the life cycle of the

service. The SCM also controls how other applications can control the service programmatically.



■ Tip If you are using Microsoft Visual Studio, you can use the Windows Service project template to create a

Windows service. The template provides the basic code infrastructure required by a Windows service class, which

you can extend with your custom functionality.



To control your service, the SCM uses the eight protected methods inherited from the ServiceBase

class described in Table 14-5. You should override these virtual methods to implement the functionality

and behavior required by your service. Not all services must support all control messages. The CanXXX

properties inherited from the ServiceBase class declare to the SCM which control messages your service

supports; Table 14-5 specifies the property that controls each operation.

Table 14-5. Methods That Control the Operation of a Service



Method



Description



OnStart



All services must support the OnStart method, which the SCM calls to start the

service. The SCM passes a string array containing arguments specified for the

service. These arguments can be specified when the ServiceController.Start

method is called, and are usually configured in the service’s property window in the

Windows Control Panel. However, they are rarely used, because it is better for the

service to retrieve its configuration information directly from the Windows registry.

The OnStart method must normally return within 30 seconds, or else the SCM will

abort the service. Your service must call the RequestAdditionalTime method of the

ServiceBase class if it requires more time; specify the additional milliseconds

required as an int.



OnStop



Called by the SCM to stop a service—the SCM will call OnStop only if the CanStop

property is set to true.



OnPause



Called by the SCM to pause a service—the SCM will call OnPause only if the

CanPauseAndContinue property is set to true.



OnContinue



Called by the SCM to continue a paused service—the SCM will call OnContinue only if

the CanPauseAndContinue property is set to true.



OnShutdown



Called by the SCM when the system is shutting down—the SCM will call OnShutdown

only if the CanShutdown property is set to true.



OnPowerEvent



Called by the SCM when a system-level power status change occurs, such as a laptop

going into suspend mode. The SCM will call OnPowerEvent only if the

CanHandlePowerEvent property is set to true.



700



www.it-ebooks.info



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

14-5. Search the Windows Registry

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

×