一 注册表编程
1 什么事注册表
存放计算机运行方式的配置信息的树状表。其中包括Windows操作系统配信息,应用程序配置信息,专用用户设备配置信息,环境配置信息等。
开始-运行 regedit 可以打开注册表
2 编程相关的类
位于名称空间Microsoft.Win32;
Registry和RegistryKey
它们都是sealed类,即不能被继承;
示例程序:RegModify.rar;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 注册表
{
class RegistryUtil
{
public static string GetRegGpsCommPort()
{
string multi = GetRegValue(@"System\CurrentControlSet\GPS Intermediate Driver\Multiplexer", "DriverInterface").Trim();
if (multi != "") return multi;
string driver = GetRegValue(@"System\CurrentControlSet\GPS Intermediate Driver\Drivers", "CurrentDriver").Trim();
if (driver != "")
{
string comm = GetRegValue(@"System\CurrentControlSet\GPS Intermediate Driver\Drivers\" + driver, "CommPort").Trim();
return comm;
}
return "";
}
public static void SetRegValue(string sub,string name,string value)
{
SetRegValue(null, sub, name, value);
}
public static void SetRegValue(RegistryKey Key,string sub,string name,string value)
{
if (Key == null)
Key = Registry.LocalMachine;
RegistryKey myreg = Key.OpenSubKey(sub, true);//该项必须存在
myreg.SetValue(name, value);
Key.Close();
}
public static string GetRegValue(string sub,string name)
{
return GetRegValue(null, sub, name);
}
public static string GetRegValue(RegistryKey Key,string sub,string name )
{
string info = "";
try
{
if (Key == null)
Key = Registry.LocalMachine;
RegistryKey myreg = Key.OpenSubKey(sub);
info = myreg.GetValue(name).ToString();
myreg.Close();
}
catch(Exception ex)
{
string s = ex.Message;
}
return info;
}
public static void DeleteKey(RegistryKey Key,string sub,string name)
{
if (Key == null)
Key = Registry.LocalMachine;
RegistryKey delKey = Key.OpenSubKey(sub, true);
delKey.DeleteValue(name);
delKey.Close();
}
#region 几个示例
private static bool IsRegItemExist()
{
string[] subkeyNames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE");
subkeyNames = software.GetSubKeyNames();
//取得该项下所有子项的名称系列,并传递给预定的数组中
foreach(string keyName in subkeyNames)//遍历整个数组
{
if(keyName=="test")//判断子项的名称
{
hkml.Close();
return true;
}
}
hkml.Close();
return false;
}
private static bool IsRegKeyExit()
{
string[] subkeyNames;
RegistryKey hkml = Registry.LocalMachine;
RegistryKey software = hkml.OpenSubKey("SOFTWARE\\test");
subkeyNames = software.GetValueNames();
//取得该项下所有键值的名称的系列,并传递给预定的数组中
foreach(string keyName in subkeyNames)
{
if(keyName=="test")//判断键值的名称
{
hkml.Close();
return true;
}
}
hkml.Close();
return false;
}
#endregion
}
}