Archive for Luglio 31st, 2008

Class for write and read Strings to Registry

CodeKeep C# Feed Luglio 31st, 2008

Description: This is a class for Registryaccess, so far only string values are supported.

Link: http://www.codekeep.net/snippets/5fe1259d-b0eb-4e25-b80a-ad8804c32b44.aspx

  /// <summary>
  /// Class for Registry String Access.
  /// </summary>
  class CREGISTRYACCESS
  {
    // Konstanten
    private const string SOFTWARE_KEY = "Software";
    private const string COMPANY_NAME = "Florianus";
    private const string APPLICATION_NAME = "Protec";
    /// <summary>
    /// Method to read string value.
    /// </summary>
    /// <param name="sKey">Der Schlüsselwert.</param>
    /// <param name="sDefaultValue">Standard value.</param>
    /// <returns>the value</returns>
    static public string GetStringRegistryValue(string sKey, string sDefaultValue)
    {
      RegistryKey rkCompany;
      RegistryKey rkApplication;
      rkCompany = Registry.CurrentUser.OpenSubKey(SOFTWARE_KEY, false).OpenSubKey(COMPANY_NAME, false);
      if (rkCompany != null)
      {
        rkApplication = rkCompany.OpenSubKey(APPLICATION_NAME, true);
        if (rkApplication != null)
        {
          foreach (string sRKey in rkApplication.GetValueNames())
          {
            if (sRKey == sKey)
            {
              return (string)rkApplication.GetValue(sRKey);
            }
          }
        }
      }
      return sDefaultValue;
    }
    /// <summary>
    /// Method to write string value.
    /// </summary>
    /// <param name="sKey">The Key.</param>
    /// <param name="sStringValue">The value.</param>
    static public void SetStringRegistryValue(string sKey, string sStringValue)
    {
      RegistryKey rkSoftware;
      RegistryKey rkCompany;
      RegistryKey rkApplication;

      rkSoftware = Registry.CurrentUser.OpenSubKey(SOFTWARE_KEY, true);
      rkCompany = rkSoftware.CreateSubKey(COMPANY_NAME);

      if (rkCompany != null)
      {
        rkApplication = rkCompany.CreateSubKey(APPLICATION_NAME);
        if (rkApplication != null)
        {
          rkApplication.SetValue(sKey, sStringValue);
        }
      }
    }
  }

deneme