0 Comments

Nice generic read value from registry function on: http://www.codeproject.com/KB/dotnet/frameworkversiondetection.aspx
Function can be called like:

using System;
using Microsoft.Win32;
using NUnit.Framework;
using Ada.Cdf.Common;

namespace Ada.Cdf.Test.Common
{
    [TestFixture]
    public class RegistryHelperTester
    {
        [Test]
        public void GetRegistryValueTest()
        {
            string data = string.Empty;

            // Read a registry key value
            bool result = RegistryHelper.GetRegistryValue<string>(RegistryHive.LocalMachine,@"SOFTWARE\Microsoft\Windows\CurrentVersion","ProgramFilesDir", RegistryValueKind.String, out data);

            // Show result
            Console.WriteLine(data);
        }
    }
}


Result on my machine

C:\Program Files (x86)

using System;
using System.Globalization;
using Microsoft.Win32;

namespace Ada.Cdf.Common
{
    public class RegistryHelper
    {
        /// <summary>
        /// Read the value of a key from registry
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="hive"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="kind"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static bool GetRegistryValue<T>(RegistryHive hive, string key, string value, RegistryValueKind kind, out T data)
        {
            bool success = false;
            data = default(T);

            using (RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(hive, String.Empty))
            {
                if (baseKey != null)
                {
                    using (RegistryKey registryKey = baseKey.OpenSubKey(key, RegistryKeyPermissionCheck.ReadSubTree))
                    {
                        if (registryKey != null)
                        {
                            // If the key was opened, try to retrieve the value.
                            RegistryValueKind kindFound = registryKey.GetValueKind(value);
                            if (kindFound == kind)
                            {
                                object regValue = registryKey.GetValue(value, null);
                                if (regValue != null)
                                {
                                    data = (T)Convert.ChangeType(regValue, typeof(T), CultureInfo.InvariantCulture);
                                    success = true;
                                }
                            }
                        }
                    }
                }
            }
            return success;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts