Accessing the Windows Registry

PC Repair Tools

Advanced Registry Cleaner PC Diagnosis and Repair

Get Instant Access

Although you didn't have direct access to the Windows Registry using server-side script in classic ASP, several aftermarket controls provided that capability. You could also use some other language such as classic VB, which provided an easy way to read, write, and delete values from the Windows Registry using the SaveSetting, GetSetting, GetAllSettings, and DeleteSetting statements—but all the values resided in a specific key. In other words, there was no built-in way to read or write values from any other location in the Registry. But the need was there, so people used the Windows API calls from VB, which was awkward. C and C++ had fewer problems, but reading and writing to the Registry via API calls was not simple. Fortunately, the .NET framework solves that problem. In the Microsoft Win32 namespace, you'll find a Registry class that (as you might expect) wraps and simplifies access to the Registry. It's now child's play to read and write Registry values.

The Registry consists of several "hives" that contain class, machine, user, and configuration data. On a Windows 2000 server, the top-level hive names are as follows:

■ HKEY_CLASSES_ROOT

■ HKEY_CURRENT_USER

■ HKEY_LOCAL_MACHINE

■ HKEY_CURRENT_CONFIG

■ HKEY_PERFORMANCE_DATA

Windows 98/ME exposes an additional key, the hkey_dyn_data key, which is intended to hold data that changes frequently.

You don't need to create a Registry object. The Registry class has no methods. Instead, it exposes each of these root keys as separate static properties that return RegistryKey objects:

RegistryKey localMachineRoot = Registry.LocalMachine; RegistryKey classesRoot = Registry.ClassesRoot;

In ASP applications, people often used the Registry to store application initialization and configuration values. You no longer need to do this in .NET because you can—and should—use the Web.config file <appSettings> section instead; I've included this section for people who need to read existing settings from their Registries.

Tip I recommend that you use your application's Web.config file rather than the Windows Registry to store application initialization and configuration values.

The Web Form chio-io.aspx shows how to read, write, and update Registry keys. It modifies only the contents of the key Software\Sybex\CSharpASP in the hkey_current_user hive. The Web Form displays any existing subkeys and values in the csharpASP key and lets you add new values and modify or delete existing values.

Warning The code in the chio-io.aspx.cs Web Form's Page_Load method accesses the Registry. You will need to apply sufficient permissions to the Registry key hkey_local_machine\software on your server to allow the ASP.NET account or your logon account to create, read, and write the Sybex subkey. You can set Registry permissions using the regedt32.exe program that ships with Windows.

Warning Modifying the Registry can cause your server to fail if you change critical settings or alter security so that you can't read or write the Registry.

When you run the Web Form, the Page_Load event first checks to see if the

HKEY_cuRRENT_usER\Software\Sybex Registry key exists.

private RegistryKey m keySybex; m keySybex = Registry.LocalMachine.OpenSubKey _ ("SOFTWARE\\Sybex", true);

The OpenSubKey method returns null if the key does not exist. In this example, if the key doesn't exist, the code creates it:

m keySybex = Registry.LocalMachine.CreateSubKey _ ("SOFTWARE\\Sybex");

catch (Exception ex) {

Response.Write(ex.Message); Response.End();

In contrast, the CreateSubKey method can throw any of several exceptions if the create operation fails.

After creating or opening the HKEY_cuRRENT_USER\Software\Sybex\ subkey, the code repeats the test-create operation with the CSharpASP subkey.

m_keyCSharpASP= m_keySybex.OpenSubKey("CSharpASP", true); if (m_keyCSharpASP == null ) { try {

m_keySybex.CreateSubKey("CSharpASP"); m keyCSharpASP = m keySybex.OpenSubKey _ ("CSharpASP", true);

catch (Exception ex) {

Response.Write(ex.Message); Response.End();

Because of this code, at the end of the Page_Load routine, the Web Form always has a reference to the CSharpASP key in the m_keyCSharpASP variable.

Each key in the Registry may contain subkeys—much like an XML document. The fillSubKeys method reads any subkeys that exist and stores the subkey names in the string array variable m subkeys().

private void fillSubKeys() { try {

m subKeys = m keyCSharpASP.GetSubKeyNames();

catch (Exception ex) {

Response.Write(ex.Message); Response.End();

The Web Form contains a ListBox that displays the keys. When a user clicks a key name in the ListBox, the Web Form automatically posts the selection to the server, retrieves the value of the selected subkey, and displays the key name and value in two TextBoxes so that the user can view or edit the value for that subkey. The simplest way to fill the ListBox is to databind it to the m_subkeys () array, which the Web Form does during the initial page load.

ListKeys.DataSource = m subKeys; ListKeys.DataBind();

The Web Form then is displayed. Because the ListBox's AutoPostBack property is set to true, the form gets posted each time a user selects an item in the ListBox. That fires the

SelectedindexChanged event on the server, which retrieves the key and value for the selected item and sets the contents of the TextKey and TextValue TextBoxes to the selected key name and value.

private void ListKeys SelectedIndexChanged(object sender, System.EventArgs e) { RegistryKey aKey; int anIndex;

String aName;

anIndex = ListKeys.SelectedIndex; if (anIndex >= 0) {

aName = ListKeys.Items[anIndex].Text; TextKey.Text = aName; // set the subkey aKey = m keyCSharpASP.OpenSubKey(aName); // retrieve the default value

TextValue.Text = (String) aKey.GetValue(null); aKey.Close();

The GetValue method in the next-to-last line in the if block accepts a value name. Note that the code passes the value null, which retrieves the default value of the key. This example uses only the default value for each subkey.

Note All keys have at least one value—a default, unnamed value, which you can retrieve by passing null to the getValue method—but keys may have multiple named values. If you need to access a key with multiple values, you can retrieve the value names using the GetValueNames method and then retrieve any individual value using the getValue method.

There are two buttons on the Web Form—Delete and Add/Update. Clicking Delete posts the form. The Web Form tests to see if the key specified in the TextKey field exists. If so, it deletes the key; otherwise, it displays a client-side alert. You'll see more about sending client-side script like this in Chapter 24, "Efficiency and Scalability."

private void btnDelete Click(object sender, System.EventArgs e) { String aName; RegistryKey aKey; aName = TextKey.Text; if (aName != "") { // set the subkey aKey = m keyCSharpASP.OpenSubKey(aName); if (aKey_!= null) { aKey.Close();

m_keyCSharpASP.DeleteSubKey(aName); // clear the text boxes TextKey.Text = null; TextValue.Text = null; // reset the listbox ListKeys.ClearSelection(); fillSubKeys();

ListKeys.DataSource = m subKeys; ListKeys.DataBind();

RegisterStartupScript("BadKey", "<script type=\"text/javascript\">" + "alert('The key you entered does not " + "exist.');</script>");

When the user clicks the Add/Update button, the Web Form fires the btnAdd_Click event. That method retrieves the key name from the TextKey field and calls the CSharpASP key's CreateSubKey method. If the key already exists, the method retrieves it. If the key does not exist, the method creates it. In either case, the method returns the subkey, which btnAdd_Click then uses to set the default value to the text entered by the user in the TextValue field.

private void btnAdd Click(object sender, System.EventArgs e) { RegistryKey aKey; String aKeyName;

String aValue; aKeyName = TextKey.Text; aValue = TextValue.Text; if (aKeyName != null) {

aKey = m keyCSharpASP.CreateSubKey(aKeyName); if (aKey_!= null) {

aKey.SetValue(null, aValue); aKey.Close();

ListKeys.ClearSelection(); fillSubKeys();

ListKeys.DataSource = m subKeys; ListKeys.DataBind();

In both the btnDelete_click and btnAdd_click events, note that the code calls the fillSubKeys method and rebinds the ListKeys ListBox if the event changes the Registry. Otherwise, the ASP.NET engine restores the ListBox from the _viewstate data. Listing 10.8 shows the full code.

Listing 10.8: The Web Form ch10-10.aspx.cs Code using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using Microsoft.Win32;

namespace CSharpASP.ch10 { /// <summary>

/// Summary description for ch10 10. /// </summary>

public class ch10 10 : System.Web.UI.Page {

protected System.Web.UI.WebControls.ListBox ListKeys; protected System.Web.UI.WebControls.Button btnAdd; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.Label Label3; protected System.Web.UI.WebControls.TextBox TextKey; protected System.Web.UI.WebControls.TextBox TextValue;

protected System.Web.UI.WebControls.Button btnDelete; private RegistryKey m keySybex; private RegistryKey m keyCSharpASP; private String[] m subKeys;

private void Page Load(object sender, System.EventArgs e) { RegistryKey x;

x = Registry.PerformanceData; if (x==null) {

Response.Write("x is null"); Response.End();

m keySybex =

Registry.LocalMachine.OpenSubKey ("SOFTWARE\\Sybex", true); if (m keySybex == null ) { try {

m keySybex = Registry.LocalMachine. CreateSubKey("SOFTWARE\\Sybex");

catch (Exception ex) {

Response.Write(ex.Message); Response.End();

m keyCSharpASP= m keySybex.OpenSubKey

_("CSharpASP", true); if (m_keyCSharpASP == null ) { try {

m_keySybex.CreateSubKey("CSharpASP"); m keyCSharpASP = m keySybex.OpenSubKey _ ("CSharpASP", true);

catch (Exception ex) {

Response.Write(ex.Message); Response.End();

fillSubKeys(); if (IlsPostBack) {

ListKeys.DataSource = m subKeys; ListKeys.DataBind();

private void fillSubKeys() { try {

m subKeys = m keyCSharpASP.GetSubKeyNames();

catch (Exception ex) {

Response.Write(ex.Message); Response.End();

public override void Dispose() {

if (m_keyCSharpASP != null) { m_keyCSharpASP.Close();

base.Dispose();

#region Web Form Designer generated code override protected void OnInit(EventArgs e) { //

// CODEGEN: This call is required by the

InitializeComponent(); base.Onlnit(e);

/// Required method for Designer support -/// do not modify

/// the contents of this method with the code editor. /// </summary>

private void InitializeComponent() {

this.ListKeys.SelectedlndexChanged += new System.EventHandler

(this.ListKeys SelectedlndexChanged); this.btnAdd.Click += new

System.EventHandler(this.btnAdd Click); this.btnDelete.Click += new

System.EventHandler(this.btnDelete Click); this.Load += new

System.EventHandler(this.Page Load);

#endregion private void ListKeys SelectedlndexChanged (object sender, System.EventArgs e) { RegistryKey aKey; int anlndex; String aName;

anlndex = ListKeys.Selectedlndex; if (anlndex >= 0) {

aName = ListKeys.Items[anIndex].Text; TextKey.Text = aName; // set the subkey aKey = m keyCSharpASP.OpenSubKey(aName); // retrieve the default value

TextValue.Text = (String) aKey.GetValue(null); aKey.Close();

private void btnDelete Click(object sender, System.EventArgs e) { String aName; RegistryKey aKey; aName = TextKey.Text; if (aName != "") { // set the subkey aKey = m keyCSharpASP.OpenSubKey(aName); if (aKey_!= null) { aKey.Close();

m_keyCSharpASP.DeleteSubKey(aName); // clear the text boxes TextKey.Text = null; TextValue.Text = null; // reset the listbox ListKeys.ClearSelection(); fillSubKeys();

ListKeys.DataSource = m subKeys; ListKeys.DataBind();

RegisterStartupScript("BadKey",

"<script type=\"text/javascript\">" + "alert('The key you entered does not " + "exist.');</script>");

private void btnAdd Click(object sender, System.EventArgs e) { RegistryKey aKey; String aKeyName;

String aValue; aKeyName = TextKey.Text; aValue = TextValue.Text; if (aKeyName != null) {

aKey = m keyCSharpASP.CreateSubKey(aKeyName); if (aKey_!= null) {

aKey.SetValue(null, aValue); aKey.Close();

ListKeys.ClearSelection(); fillSubKeys();

ListKeys.DataSource = m subKeys; ListKeys.DataBind();

Was this article helpful?

0 0

Post a comment