/// <summary> /// 注册表操作类 /// </summary> public static class RegistryKeyOperator { public const string Extension = ".space"; /// <summary> /// 创建文件关联注册表 已存在则跳过 /// </summary> public static void CreatFileLinkRegistry() { if (MatchRegistryKey()) return; try { //文件注册 var registryKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(Extension); //设置默认图标 var iconKey = registryKey?.CreateSubKey("DefaultIcon"); if (iconKey == null) return; iconKey.SetValue("", Application.StartupPath + "\Image.ico"); //设置默认打开程序路径 var comRegistryKey = registryKey.CreateSubKey("shell\open\command"); if (comRegistryKey == null) return; comRegistryKey.SetValue("", Application.ExecutablePath + " %1"); //关闭 registryKey.Close(); } catch { MessageBox.ShowError("请以管理员身份运行此程序!"); } } private static bool MatchRegistryKey() { //获取信息 var registryKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(Extension); if (registryKey?.OpenSubKey("shell")?.OpenSubKey("open")?.OpenSubKey("command") == null) return false; var comRegistryKey = registryKey.OpenSubKey("shell")?.OpenSubKey("open")?.OpenSubKey("command"); var varValue = comRegistryKey?.GetValue(""); if (Equals(varValue, Application.ExecutablePath + " %1")) { return true; } Microsoft.Win32.Registry.ClassesRoot.DeleteSubKeyTree(Extension, false); return false; } }