C# 操作注册表

  
        //Get Registry item value of key, item name=name
        public string GetValue(RegistryKey rootKey, string path, string itemName)
        {
            if (string.IsNullOrEmpty(itemName) || rootKey == null || string.IsNullOrEmpty(path)) return null;

            try
            {
                RegistryKey regKey = rootKey.OpenSubKey(path, false);
                if (regKey != null)
                {
                    string itemValue = regKey.GetValue(itemName) == null ? null : regKey.GetValue(itemName).ToString();

                    if (!string.IsNullOrEmpty(itemValue))
                    {
                        regKey.Close();
                        return itemValue;
                    }
                }
            }
            catch (Exception ex)
            {
rootKey.Close();
throw ex; } return null; #region Sample Code for Get item Value //string serverTypeRegPath = @"SYSTEM\CurrentControlSet\Services\W32Time\Parameters"; //string itemName = "Type"; //RegistryKey rootKey = Registry.LocalMachine; //string strServerType = this.GetValue(rootKey, serverTypeRegPath, itemName); #endregion }

 

 

  //Set registry item value of key, item name=item name, item value=itemValue, item value type=itemValueTime
        //If the item dose not exixted, create the item and set the value
        public void SetValue(RegistryKey rootKey, string path, string itemName,
            RegistryValueKind itemValueKind, string itemValue)
        {
            if (rootKey == null || string.IsNullOrEmpty(path) || string.IsNullOrEmpty(itemName)
                || itemValueKind == null || string.IsNullOrEmpty(itemValue))
            {
                return;
            }

            try
            {
                RegistryKey key = rootKey.OpenSubKey(path, true);
                key.SetValue(itemName, itemValue, itemValueKind);

                rootKey.Close();
            }
            catch (Exception ex)
            {
rootKey.close();
throw ex; } #region Sample Code //string serverTypeRegPath = @"SYSTEM\CurrentControlSet\Services\W32Time\Parameters"; //string itemName = "test"; //string itemValue = "xlding_1"; //RegistryKey rootKey = Registry.LocalMachine; //this.SetValue(rootKey, serverTypeRegPath, itemName, RegistryValueKind.String, itemValue); //string strXXX = this.GetValue(rootKey, serverTypeRegPath, itemName); //MessageBox.Show(strXXX); #endregion }

 

posted @ 2014-02-13 09:08  quietwalk  阅读(318)  评论(0编辑  收藏  举报