C#操作服务器(2):C#实现对注册表项的创建和读写操作
作者:陆金龙
发表时间:2015-05-24 11:42
通过C#设置(如果不存在则创建)或获取(不存在则返回空字符串)注册表项的值。
////// 设置注册表项的值 /// ///起始项 ///子项路径 ///字符串值项目的名称 ///字符串值项目的名称 public void SetRegeditValue(RegistryKey startKey, string subKeyPath, string strItemName, string strItemValue) { RegistryKey subKey = startKey.OpenSubKey(subKeyPath, true); if (subKey==null) { subKey = startKey.CreateSubKey(subKeyPath); } subKey.SetValue(strItemName, strItemValue); } ////// 获取注册表项的值 /// ///起始项 ///子项路径 ///字符串值项目的名称 public string GetRegeditValue(RegistryKey startKey, string subKeyPath, string strItemName) { RegistryKey subKey = startKey.OpenSubKey(subKeyPath, false); if (subKey == null) { return ""; } object obj = subKey.GetValue(strItemName); return obj==null?"":obj.ToString(); }
调用示例:
RegistryKey key = Microsoft.Win32.Registry.LocalMachine
SetRegeditValue(key,@"SOFTWARE\Kinglong\IprogramCMS","UserName","king");
string userName =GetRegeditValue(key,@"SOFTWARE\Kinglong\IprogramCMS","UserName");