您的位置:首页 > 编程语言 > C#

Operating the registry help class(C#读写注册表操作)

2012-08-08 09:38 621 查看
/// <summary>

/// Operating the registry help class

/// </summary>

public class RegistryHelper

{

/// <summary>

/// Gets value by access registry in 'CurrentUser' path

/// </summary>

/// <param name="regPath">registry path</param>

/// <param name="key">registry key</param>

/// <returns>registry value</returns>

public static string GetRegByCurrentUserValue(string regPath, string key)

{

string res = string.Empty;

try

{

RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(regPath, RegistryKeyPermissionCheck.Default, System.Security.AccessControl.RegistryRights.ReadKey);

if (registryKey != null)

{

var value = registryKey.GetValue(key);

res = value == null ? string.Empty : value.ToString();

registryKey.Close();

}

}

catch

{

return string.Empty;

}

return res;

}

/// <summary>

/// Gets value by access registry in 'LocalMachine' path

/// </summary>

/// <param name="regPath">registry path</param>

/// <param name="key">registry key</param>

/// <returns>registry value</returns>

public static string GetRegByLocalMachineValue(string regPath, string key)

{

string res = string.Empty;

try

{

RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(regPath,RegistryKeyPermissionCheck.Default,System.Security.AccessControl.RegistryRights.ReadKey);

if (registryKey != null)

{

var value = registryKey.GetValue(key);

res = value == null ? string.Empty : value.ToString();

registryKey.Close();

}

}

catch (Exception ex)

{

LogHelper.WriteException(ex);

return string.Empty;

}

return res;

}

/// <summary>

/// insert or update registry value in 'CurrentUser' path

/// </summary>

/// <param name="regPath">registry path</param>

/// <param name="key">registry key</param>

/// <param name="setValue">registry value</param>

/// <returns>bool</returns>

public static bool ToInsertOrUpdateKey(string regPath, string key, string setValue)

{

bool res = false;

try

{

RegistryKey registryKey = Registry.CurrentUser.OpenSubKey(regPath, true);

if (registryKey == null)

{

//Create KEY

registryKey = Registry.CurrentUser.CreateSubKey(regPath);

}

if (registryKey != null)

{

//update Key,value

registryKey.SetValue(key, setValue);//not exists add

res = true;

registryKey.Close();

}

}

catch

{

return false;

}

return res;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: