c# - 读取注册表信息

来源:互联网 发布:java局部变量初始化 编辑:程序博客网 时间:2024/05/20 11:49

使用c# Microsoft.Win32.Registry 可以很简单的对注册表进行读写, 同时此API还支持修改Remote Machine的注册表信息。

请看代码:

using Microsoft.Win32;        //regLocation:@"SOFTWARE\XXXX\EnvSetterServer"        //keyName:TestAgentConfigPath        public static string ReadRegistryKey(string regLocation, string keyName)        {            string keyValue = null;            try            {                RegistryKey rk = Registry.LocalMachine.CreateSubKey(regLocation);                if (rk.GetValue(keyName) != null)                {                    keyValue = rk.GetValue(keyName).ToString();                }                return keyValue;            }            catch (Exception ex)            {                return null;                throw ex;            }        }        //regLocation:@"SOFTWARE\XXXX\EnvSetterServer"        //keyName:TestAgentConfigPath        //keyValue:@"c:\tete\tete.exe"        public static void WriteAKeyToRegistry(string regLocation, string keyName, string keyValue)        {            try            {                RegistryKey rk = Registry.LocalMachine.CreateSubKey(regLocation);                rk.SetValue(keyName, keyValue, RegistryValueKind.String);                rk.Close();            }            catch (Exception ex)            {                throw ex;            }        }        //remoteMachine:MachineName        //regLocation:@"SOFTWARE\XXXX\EnvSetterServer"        //keyName:TestAgentConfigPath        public static string ReadRemoteRegistryKey(string remoteMachine, string regLocation, string keyName)        {            string keyValue = null;            try            {                RegistryKey rk = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, remoteMachine).OpenSubKey(regLocation);                if (rk.GetValue(keyName) != null)                {                    keyValue = rk.GetValue(keyName).ToString();                }                return keyValue;            }            catch (Exception ex)            {                return null;                throw ex;            }        }

详细信息可以参考:http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx


原创粉丝点击