We help IT Professionals succeed at work.

Config file vs registry C#

GVNPublic123
GVNPublic123 asked
on
253 Views
Last Modified: 2012-05-08
Hello,

I've been using .config file to store licensing information for users of my software, but I've found out this is not the best way to do it. It does not require elevation on Vista, 7, but it wouldn't work with my demo prototype as if executable would be moved, demo values would reset.

Therefore, I'm looking for registry. Is there any way to store licensing information in registry WITHOUT need of application elevation?

Thanks.
Comment
Watch Question

Author

Commented:
I was thinking if I make registry entries at install point, and than just edit them in application, would that work out so user does not need to elevate each time app is used?
Meir RivkinFull stack Software Engineer
CERTIFIED EXPERT

Commented:
here's a registry wrapper helper class that i'm using:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using Microsoft.Win32;
 
[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_LOCAL_MACHINE")]
 
namespace Utils
{
    public class AppRegWrapper
    {
        #region Constants
        const string CONFIG_PHYSICAL_DIR = "InstallationFolder";
        const string MYAPP_SUBKEY = @"SOFTWARE\MyApp";
        const string ROOT_SUBKEY = @"SOFTWARE";
        #endregion
 
        #region Internal
        private static AppRegWrapper _instance = null;
        #endregion
 
        #region Ctor
        /// <summary>
        /// Initializes the <see cref="AppRegWrapper"/> class.
        /// </summary>
        private AppRegWrapper()
        {
 
        }
        #endregion
 
        #region Static
        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static AppRegWrapper Instance
        {
            get
            {
                if (AppRegWrapper._instance == null)
                {
                    AppRegWrapper._instance = new AppRegWrapper();
                }
 
                return AppRegWrapper._instance;
            }
        }
        #endregion
 
        #region Methods
 
        #region Public
 
        /// <summary>
        /// Cleans the registry.
        /// </summary>
        public void CleanRegistry()
        {
            Console.WriteLine("Clean registry: {0}", MYAPP_SUBKEY);
            string regPath = ROOT_SUBKEY;
 
            using (RegistryKey regkey = Registry.LocalMachine.OpenSubKey(regPath, true))
            {
                if (regkey == null)
                {
                    throw new Exception("Invalid key");
                }
 
                if (regkey.GetSubKeyNames().Contains("MyApp", StringComparer.OrdinalIgnoreCase))
                {
                    regkey.DeleteSubKey("MyApp");
                    Console.WriteLine("DeleteSubKey: MyApp");
                    regkey.Close();
                }
            }
        }
 
        /// <summary>
        /// Sets the product params.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public void SetProductParams(string product, string key, string value)
        {
            string productKey = MYAPP_SUBKEY + "\\" + product;
            using (RegistryKey keyRoot = Registry.LocalMachine.OpenSubKey(productKey, true))
            {
                if (keyRoot == null)
                {
                    throw new Exception("Invalid key");
                }
 
                SetProductParams(keyRoot, key, value);
                keyRoot.Close();
            }
        }
 
        /// <summary>
        /// Sets the product parameters.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <param name="productExParams">The productExParams.</param>
        public void SetProductParams(string product, Dictionary<string, string> productExParams)
        {
            foreach (KeyValuePair<string, string> item in productExParams)
            {
                SetProductParams(product, item.Key, item.Value);
            }
        }
 
        /// <summary>
        /// Gets the product param.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <returns></returns>
        public Dictionary<string, string> GetProductParams(string product)
        {
            Dictionary<string, string> prodParams = new Dictionary<string, string>();
 
            string productKey = MYAPP_SUBKEY + "\\" + product;
            using (RegistryKey keyRoot = Registry.LocalMachine.OpenSubKey(productKey, true))
            {
                if (keyRoot == null)
                {
                    throw new Exception("Invalid key");
                }
 
                foreach (string key in keyRoot.GetValueNames())
                {
                    string value = keyRoot.GetValue(key).ToString();
                    Console.WriteLine("key: {0}, value: {1}", key, value);
                    prodParams.Add(key, value);
                }
            }
 
            return prodParams;
        }
 
        /// <summary>
        /// Gets the product param.
        /// </summary>
        /// <param name="product">The product.</param>
        /// <param name="key">The key.</param>
        /// <returns>string</returns>
        public string GetProductParam(string product, string key)
        {
            string productKey = MYAPP_SUBKEY + "\\" + product;
            using (RegistryKey keyRoot = Registry.LocalMachine.OpenSubKey(productKey, true))
            {
                if (keyRoot == null)
                {
                    throw new Exception("Invalid key");
                }
 
                object value = keyRoot.GetValue(key);
                keyRoot.Close();
 
                if (value == null)
                {
                    throw new Exception("Invalid value");
                }
 
                return value.ToString();
            }
        }
 
        /// <summary>
        /// Removes the product.
        /// </summary>
        /// <param name="product">The product.</param>
        public void RemoveProduct(string product)
        {
            Console.WriteLine("Remove product: {0}", product);
            using (RegistryKey keyRoot = Registry.LocalMachine.OpenSubKey(MYAPP_SUBKEY, true))
            {
                keyRoot.DeleteSubKey(product);
                keyRoot.Close();
            }
        }
 
 
        /// <summary>
        /// Creates the product root.
        /// </summary>
        /// <param name="product">The product.</param>
        public void CreateProductRoot(string product)
        {
            CreateRoot();
 
            Console.WriteLine("Create registry product root: {0}", product);
            string regPath = ROOT_SUBKEY;
 
            using (RegistryKey regkey = Registry.LocalMachine.OpenSubKey(regPath, true))
            {
                if (regkey == null)
                {
                    throw new Exception("Invalid key");
                }
 
                if (!regkey.GetSubKeyNames().Contains("MyApp", StringComparer.OrdinalIgnoreCase))
                {
                    throw new Exception("Invalid key");
                }
 
                using (RegistryKey rootKey = regkey.OpenSubKey("MyApp", true))
                {
                    rootKey.CreateSubKey(product, RegistryKeyPermissionCheck.ReadWriteSubTree);
                    rootKey.Close();
                }
 
                regkey.Close();
            }
        }
 
        /// <summary>
        /// Sets the registry settings.
        /// </summary>
        /// <param name="keyPath">The key path.</param>
        /// <param name="keyName">Name of the key.</param>
        /// <param name="keyValue">The key value.</param>
        /// <returns>bool</returns>
        public static bool SetRegistrySettings(string keyPath, string keyName, string keyValue)
        {
 
            object currentValue = Registry.GetValue(keyPath, keyName, null);
            if (currentValue == null)
            {
                Console.WriteLine(string.Format("[Error] Set registry key [{0} - {1}] failed.", keyPath, keyName));
                return false;
            }
 
            Console.WriteLine(string.Format("new value: {0}", keyValue));
            Console.WriteLine(string.Format("currentValue: {0}", currentValue));
 
            if (currentValue.ToString() != keyValue)
            {
                Registry.SetValue(keyPath, keyName, keyValue);
                Console.WriteLine(string.Format("Set registry key [{0} - {1}: {2}].", keyPath, keyName, keyValue));
 
                object objValue = Registry.GetValue(keyPath, keyName, null);
                if (objValue == null)
                {
                    Console.WriteLine(string.Format("[Error] Validate registry key[{0} - {1}] failed.", keyPath, keyName));
                    return false;
                }
 
                if (objValue.ToString() != keyValue)
                {
                    Console.WriteLine(string.Format("[Error] Set registry key [{0} - {1}] failed", keyPath, keyName));
                    return false;
                }
            }
            else
            {
                Console.WriteLine(string.Format("Set registry key [{0} - {1}] skipped, value not changes.", keyPath, keyName));
            }
 
            return true;
 
        }
        #endregion
 
        #region Private
        /// <summary>
        /// Creates the root.
        /// </summary>
        private void CreateRoot()
        {
            Console.WriteLine("Create registry root");
            string regPath = ROOT_SUBKEY;
 
            using (RegistryKey regkey = Registry.LocalMachine.OpenSubKey(regPath, true))
            {
                if (regkey == null)
                {
                    throw new Exception(string.Format("Invalid registry key.", regPath));
                }
 
                if (!regkey.GetSubKeyNames().Contains("MyApp", StringComparer.OrdinalIgnoreCase))
                {
                    regkey.CreateSubKey("MyApp", RegistryKeyPermissionCheck.ReadWriteSubTree);
                    regkey.Close();
                }
            }
        }
 
        /// <summary>
        /// Sets the product params.
        /// </summary>
        /// <param name="prodKey">The prod key.</param>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        private void SetProductParams(RegistryKey prodKey, string key, string value)
        {
            string[] settings = prodKey.GetSubKeyNames();
 
            Console.WriteLine("Key: {0}\tValue: {1}", key, value);
            if (!settings.Contains(key))
            {
                prodKey.SetValue(key, value);
            }
        }
        #endregion
 
        #endregion
    }
}

Open in new window

Anurag ThakurTechnical Manager

Commented:
licensing information is never kept in the config files only the version of the application can be kept in the config files for reference purposes

you can add the values to the registry and retrieve them on need basis
example for licensing you an add an entry in the registry when the application is installed and when it was first used and accordingly take action to enable the application if the licensing terms and conditions are met or disable the application if the application is not licensed or the application license has expired

Author

Commented:
Ok, last thing. What should path be like?
I don't want to elevate the application to create/edit/write/delete keys, so maybe something like CURRENT_USER?
Or it would also work for all users on machine?

Also, what path should I go for? Company name, product name, what are expert suggestions? So I wont regret later on.
Anurag ThakurTechnical Manager

Commented:
if you use company name, product name etc in the registry then that can be easily found out by the users and then can be tempered with
my recommendation will be to use some encrypted formatting of the registry keys and values and even the key should not be simple one

Author

Commented:
Nah, its OK, I am always encrypting all data, so I am not worried. I think I will go company name/product

What should I be saving at, User, Current user?
Technical Manager
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.