/
一、注册表操作简介
Registry 类,RegistryKey 类提供了操作注册表的接口
RegistryValueKind:用于指定操作注册表的数据类型
在注册表中,最上面的节点是注册表巢(registry hive)。
- HKEY_CLASSES_ROOT(HKCR) 包含系统文件类型的细节,以及应用程序可以打开的文件类型,它还包含所有COM组件的注册信息。
- HKEY_CURRENT_USER(HKCU) 包含用户目前登陆的机器的用户配置,包括桌面设置、环境变量、网络和打印机连接和其他定义用户操作环境的变量。
- HKEY_LOCAL_MACHINE(HKLM) 是一个很大的巢,其中包含所有安装到机器上的软件和硬件的信息。
- HKEY_USERS(HKUSR) 包含所有用户的用户配置。
- HKEY_CURRENT_CONFIG(HKCF) 包含机器上硬件的信息。
Registry类封装了注册表的七个基本主键:
- Registry.ClassesRoot: 对应于HKEY_CLASSES_ROOT主键
- Registry.CurrentUser:对应于HKEY_CURRENT_USER主键
- Registry.LocalMachine:对应于 HKEY_LOCAL_MACHINE主键
- Registry.User:对应于 HKEY_USER主键
- Registry.CurrentConfig:对应于HEKY_CURRENT_CONFIG主键
- Registry.DynDa :对应于HKEY_DYN_DATA主键
- Registry.PerformanceData:对应于HKEY_PERFORMANCE_DATA主键
const string KeyName = "HKEY_CURRENT_USER\\Example";
Registry.SetValue(keyName, "", 5280);//默认名称
Registry.SetValue(keyName, "TestLong", 1234567, RegistryValueKind.QWord);
int i = (int)Registry.GetValue(keyName, "", -1);//默认值
long l = (long)Registry.GetValue(keyName, "TestLong", long.MinValue);
RegistryKey类封装了对注册表的基本操作。包括读、写、删等操作的常用函数:
- Name:键的名称(只读)
- SubKeyCount:键的子键个数
- ValueCount:键包含的值的个数
- Close():关闭键
- CreateSubKey():创建给定名称的子键
- DeleteSubKey():删除指定的子键
- DeleteSubKeyTree():递归删除子键及其所有的子键
- DeleteValue():从键中删除一个指定的值
- GetAccessControl():返回指定注册表键的访问控制表
- GetSubKeyNames():返回包含子键名称的字符串数组
- GetValue():返回指定的值
- GetValueKind();返回指定的值,检索其注册表数据类型
- GetValueNames():返回一个包含所有键值名称的字符串数组
- OpenSubKey():返回表示给定子键的RegistryKey实例引用
- SetAccessControl():把访问控制表(ACL)应用于指定的注册表键
- SetValue();设置指定的值
二、注册表项的创建、打开、删除
//使用CreateSubKey()在SOFTWARE下创建子项test
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftWare = hklm.CreateSubKey(@"SOFTWARE\test");
hklm.Close();
hkSoftWare.Close();
//使用OpenSubKey()打开项,获得RegistryKey对象,当路径不存在时,为Null。第二个参数为true,表示可写,可读,可删;省略时只能读。
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test",true);
hklm.Close();
hkSoftWare.Close();
//主要用到了DeleteSubKey(),删除test项
RegistryKey hklm = Registry.LocalMachine;
hklm.DeleteSubKey(@"SOFTWARE\test", true); //为true时,删除的注册表不存在时抛出异常;当为false时不抛出异常。
hklm.Close();
三、注册表键值的创建、打开和删除
//主要用到了SetValue(),表示在test下创建名称为Name,值为RegistryTest的键值。第三个参数表示键值类型,省略时,默认为字符串
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test",true);
hkSoftWare.SetValue("Name", "RegistryTest", RegistryValueKind.String);
hklm.Close();
hkSoftWare.Close();
//主要用到了GetValue(),获得名称为"Name"的键值
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test", true);
string sValue = hkSoftWare.GetValue("Name").ToString();
hklm.Close();
hkSoftWare.Close();
//主要用到了DeleteValue(),表示删除名称为"Name"的键值,第二个参数表示是否抛出异常
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE\test", true);
hkSoftWare.DeleteValue("Name", true);
hklm.Close();
hkSoftWare.Close();
四、例子:
//判断注册表项是否存在
private bool IsRegistryKeyExist(string sKeyName)
{
string[] sKeyNameColl;
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkSoftWare = hklm.OpenSubKey(@"SOFTWARE");
sKeyNameColl = hkSoftWare.GetSubKeyNames(); //获取SOFTWARE下所有的子项
foreach (string sName in sKeyNameColl)
{
if (sName == sKeyName)
{
hklm.Close();
hkSoftWare.Close();
return true;
}
}
hklm.Close();
hkSoftWare.Close();
return false;
}
//判断键值是否存在
private bool IsRegistryValueNameExist(string sValueName)
{
string[] sValueNameColl;
RegistryKey hklm = Registry.LocalMachine;
RegistryKey hkTest = hklm.OpenSubKey(@"SOFTWARE\test");
sValueNameColl = hkTest.GetValueNames(); //获取test下所有键值的名称
foreach (string sName in sValueNameColl)
{
if (sName == sValueName)
{
hklm.Close();
hkTest.Close();
return true;
}
}
hklm.Close();
hkTest.Close();
return false;
}
//开启程序自启动
string path = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.SetValue("JcShutdown", path);
rk2.Close();
rk.Close();
//关闭程序自启动
string path = Application.ExecutablePath;
RegistryKey rk = Registry.LocalMachine;
RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rk2.DeleteValue("JcShutdown", false);
rk2.Close();
rk.Close();
五、打开远程注册表
RegistryKey baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,"192.168.0.2");
RegistryKey softwareKey = key.OpenSubKey("software\\test");
softwareKey.Close();
baseKey.Close();
/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
public class ECSSetup : Editor {
#if UNITY_EDITOR_WIN
private static string unityInstallDir = string.Empty;
private const string unityTemplateDir = @"Editor\Data\Resources\ScriptTemplates";
private const string unityRegistryKey = @"Software\Unity Technologies\Installer\Unity\";
private const string unityRegistryValue = @"Location x64";
#elif UNITY_EDITOR_OSX
private const string unityInstallDir = @"/Applications/Unity/Unity.app/Contents";
private const string unityTemplateDir = @"Resources/ScriptTemplates";
#else
private const string unityInstallDir = @"/opt/Unity";
private const string unityTemplateDir = @"Editor/Data/Resources/ScriptTemplates";
#endif
private static bool enableTemplateValidation = true;
private static string TemplatePath {
get {
#if UNITY_EDITOR_WIN
if (string.IsNullOrEmpty(unityInstallDir)) {
//var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(unityRegistryKey, false);
//unityInstallDir = (string)key.GetValue(unityRegistryValue);
}
#endif
return Path.Combine(unityInstallDir, unityTemplateDir);
}
}
static readonly string[] files = {
"91-ECS__Wrapped Component Class-NewComponent.cs",
"91-ECS__Component Class-NewComponent.cs",
"91-ECS__Wrapped Component Struct-NewComponent.cs",
"91-ECS__Component Struct-NewComponent.cs",
"91-ECS__System-NewSystem.cs",
"91-ECS__ECSController-NewECSController.cs",
};
[MenuItem("ECS/Install Templates", isValidateFunction: true)]
private static bool ValidateInstallTemplates() {
if (!enableTemplateValidation)
return true;
// Only allow installation if *none* of the files exist
if (files.All(s => !File.Exists(Path.Combine(TemplatePath, s + ".txt"))) && CanCreateFileInTemplates())
return true;
return false;
}
[MenuItem("ECS/Uninstall Templates", isValidateFunction: true)]
private static bool ValidateUninstallTemplates() {
if (!enableTemplateValidation)
return true;
// To make sure we can clean up properly, check if *any* of the template files exist
if (files.Any(s => File.Exists(Path.Combine(TemplatePath, s + ".txt"))) && CanCreateFileInTemplates())
return true;
return false;
}
private static bool CanCreateFileInTemplates() {
try {
var testfile = Path.Combine(TemplatePath, ".test");
var stream = File.Create(testfile);
stream.Close();
File.Delete(testfile);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
[MenuItem("ECS/Install Templates")]
private static void InstallTemplates() {
try {
var unityDir = TemplatePath;
if(!Directory.Exists(unityDir))
{
EditorUtility.DisplayDialog("ECS Installation", "Setup not supported for your OS!\n Please copy the template folder content manually to:\n<UnityInstall>/" + unityTemplateDir + "\n\n and restart unity!", "ok");
return;
}
foreach (var file in files) {
var assetGUID = AssetDatabase.FindAssets(file)[0];
var filePath = AssetDatabase.GUIDToAssetPath(assetGUID);
File.Copy(Path.Combine(Directory.GetParent(Application.dataPath).FullName, filePath), Path.Combine(unityDir, Path.GetFileName(filePath)), true);
//var filePath = AssetDatabase.GetAssetPath();
}
EditorUtility.DisplayDialog("ECS Setup", "Installation completed!\nPlease restart unity to access all functionalities!", "ok");
}
catch (UnauthorizedAccessException)
{
EditorUtility.DisplayDialog("ECS Setup", "You need access privileges to the Unity install folder.\nStart Unity as Administrator and try again.", "ok");
}
catch (Exception ex)
{
EditorUtility.DisplayDialog("ECS Setup", "SSomething went wrong!\n\n Error:\n" + ex.Message, "ok");
}
}
[MenuItem("ECS/Uninstall Templates")]
private static void UninstallECS() {
string unityDir = TemplatePath;
if(!Directory.Exists(unityDir))
{
EditorUtility.DisplayDialog("ECS Uninstallation", "Uninstallation not supported for your OS!\n Please delete the template folder content manually from:\n<Unityinstall>/"+ unityTemplateDir + "\n\n and restart unity!", "ok");
return;
}
try {
foreach (var file in files)
{
File.Delete(Path.Combine(unityDir, file + ".txt"));
}
EditorUtility.DisplayDialog("ECS Uninstallation", "Uninstallation completed!\nPlease restart unity!", "ok");
}
catch (UnauthorizedAccessException)
{
EditorUtility.DisplayDialog("ECS Setup", "You need access privileges to the Unity install folder.\nStart Unity as Administrator and try again.", "ok");
}
catch (Exception ex)
{
EditorUtility.DisplayDialog("ECS Setup", "SSomething went wrong!\n\n Error:\n" + ex.Message, "ok");
}
}
[MenuItem("ECS/Enable Visual Debugging")]
private static void EnableVisualDebugging() {
foreach (BuildTargetGroup buildTarget in Enum.GetValues(typeof(BuildTargetGroup))) {
if (buildTarget == BuildTargetGroup.Unknown) {
continue;
}
var scriptSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget).Split(';').Where(x => !string.IsNullOrEmpty(x)).ToList();
if (!scriptSymbols.Contains("ECS_DEBUG")) {
scriptSymbols.Add("ECS_DEBUG");
}
try {
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTarget, string.Join(";", scriptSymbols.ToArray()));
} catch { }
}
}
[MenuItem("ECS/Enable Visual Debugging", isValidateFunction:true)]
private static bool ValidateEnableVisualDebugging() {
return !PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone).Contains("ECS_DEBUG");
}
[MenuItem("ECS/Disable Visual Debugging")]
private static void DisableVisualDebugging() {
foreach (BuildTargetGroup buildTarget in Enum.GetValues(typeof(BuildTargetGroup))) {
if (buildTarget == BuildTargetGroup.Unknown) {
continue;
}
var scriptSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTarget).Split(';').Where(x => !string.IsNullOrEmpty(x)).ToList();
scriptSymbols.Remove("ECS_DEBUG");
try {
PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTarget, string.Join(";", scriptSymbols.ToArray()));
} catch { }
}
}
[MenuItem("ECS/Disable Visual Debugging", isValidateFunction: true)]
private static bool ValidateDisableVisualDebugging() {
return PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone).Contains("ECS_DEBUG");
}
}
//