0
点赞
收藏
分享

微信扫一扫

C# 对注册表的读取/写入/创建/删除/判断对比代码

fbd4ffd0717b 2022-03-30 阅读 41
c#
internal class RegisterUtil
	{
		public static void initRegistry()
		{
			try
			{
				if (!RegisterUtil.ExistSubKey())
				{
					RegisterUtil.CreateSubKey();
				}
			}
			catch (Exception)
			{
			}
		}

		public static void CreateSubKey()
		{
			RegistryKey hklm = Registry.LocalMachine;
			RegistryKey hkSoftWare = hklm.CreateSubKey("SOFTWARE\\" + RegisterUtil.name);
			hklm.Close();
			hkSoftWare.Close();
		}

		public static bool ExistSubKey()
		{
			RegistryKey hklm = Registry.LocalMachine;
			RegistryKey hkSoftWare = hklm.OpenSubKey("SOFTWARE\\" + RegisterUtil.name, true);
			hklm.Close();
			if (hkSoftWare == null)
			{
				return false;
			}
			hkSoftWare.Close();
			return hkSoftWare != null;
		}

		public static void DeletedSubKey()
		{
			RegistryKey hklm = Registry.LocalMachine;
			hklm.DeleteSubKey("SOFTWARE\\" + RegisterUtil.name, true);
			hklm.Close();
		}

		public static void SetValue(string key, string value)
		{
			RegistryKey hklm = Registry.LocalMachine;
			RegistryKey hkSoftWare = hklm.OpenSubKey("SOFTWARE\\" + RegisterUtil.name, true);
			hkSoftWare.SetValue(key, value, RegistryValueKind.String);
			hklm.Close();
			hkSoftWare.Close();
		}

		public static string getValue(string key)
		{
			string result;
			try
			{
				RegistryKey hklm = Registry.LocalMachine;
				RegistryKey hkSoftWare = hklm.OpenSubKey("SOFTWARE\\" + RegisterUtil.name, true);
				object obj = hkSoftWare.GetValue(key);
				string sValue = ((obj == null) ? null : obj.ToString());
				hklm.Close();
				hkSoftWare.Close();
				result = sValue;
			}
			catch (Exception)
			{
				result = null;
			}
			return result;
		}

		public static void deleteValue(string key)
		{
			RegistryKey hklm = Registry.LocalMachine;
			RegistryKey hkSoftWare = hklm.OpenSubKey("SOFTWARE\\" + RegisterUtil.name, true);
			hkSoftWare.DeleteValue(key, true);
			hklm.Close();
			hkSoftWare.Close();
		}

		public static bool IsRegistryKeyExist(string sKeyName)
		{
			RegistryKey hklm = Registry.LocalMachine;
			RegistryKey hkSoftWare = hklm.OpenSubKey("SOFTWARE");
			string[] sKeyNameColl = hkSoftWare.GetSubKeyNames();
			foreach (string sName in sKeyNameColl)
			{
				if (sName == sKeyName)
				{
					hklm.Close();
					hkSoftWare.Close();
					return true;
				}
			}
			hklm.Close();
			hkSoftWare.Close();
			return false;
		}

		public static bool IsRegistryValueNameExist(string sValueName)
		{
			RegistryKey hklm = Registry.LocalMachine;
			RegistryKey hkTest = hklm.OpenSubKey("SOFTWARE\\" + RegisterUtil.name);
			string[] sValueNameColl = hkTest.GetValueNames();
			foreach (string sName in sValueNameColl)
			{
				if (sName == sValueName)
				{
					hklm.Close();
					hkTest.Close();
					return true;
				}
			}
			hklm.Close();
			hkTest.Close();
			return false;
		}

		public static string name = "PATH";
	}

从一个软件反编译出来的代码

举报

相关推荐

0 条评论