Friday, May 12, 2017

Selenium WebDriver – Working with the windows registry(C#)

Sometimes, we will need to interact with the OS registry to perform some basic tasks Such as getting a specific information or edit the Reg values to support the test scenarios.
תוצאת תמונה עבור ‪selenium webdriver‬‏

Registry

The most common Registry structure is as follows:

The naming convention is as follows 


Hierarchy ID
Element
Used as
1
HKEY_LOCAL_MACHINE

Root Key
2
HARDWARE
Sub Key
3
(Default)
Value
4
(value not set)
Data




















Preparations

As you probably noticed from the naming convention, there are two different classes that you will use when working with the Registry (Both are taken from the Microsoft.Win32namespace).

Registry Class

We will use it to access the root elements using a "RegistryKey" objects.

RegistryKey Class

We will use it to access any subkey in the hierarchy.

static void Main(string[] args)
{

//Phase 1: Opening the sub key
RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Mozilla\Mozilla Firefox");

//Phase 2: Getting a specific value
Console.WriteLine(Key.GetValue("CurrentVersion"));

//Phase 3: closing the sub key
Key.Close();
}

Result: 










How to write values in the registry?

The following code snippet will demonstrate how to write a new value to the registry

static void Main(string[] args)
{
//Phase 1: Create a Key in Registry (No Value is set)
RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\SeleniumExample");

//Phase 2: Write a value + Security validation
key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\SeleniumExample", RegistryKeyPermissionCheck.ReadWriteSubTree);
key.SetValue("SeleniumValue","The object data");

//Phase 3: Disposal of the object
key.Close();
}

Result: 









1 comment:

My Presentations