c#注册表对象映射
用于快捷保存与读取注册表,为对应的对象
示例
[RegistryRoot(Name = "superAcxxxxx")]
public class Abc : IRegistry
{
public string Name { get; set; } public int Age { get; set; }
}
保存
Abc a = new Abc
{
Name = "mokeyish",
Age =
};
RegistryKey register = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32); RegistryKey writeKey=register.CreateSubKey("SOFTWARE");
if (writeKey != null)
{
a.Save(writeKey);
writeKey.Dispose();
}
register.Dispose();
读取
Abc a=new Abc();
RegistryKey register = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32); RegistryKey writeKey=register.OpenSubKey("SOFTWARE");
if (writeKey != null)
{
a.Read(writeKey); writeKey.Dispose();
}
register.Dispose();
该类实现比较完善,首先使用单例模式,再加上应用程序域的退出保存策略。这样可以保存该类可以在程序退出的时候将值保存到注册表
#region summary
// ------------------------------------------------------------------------------------------------
// <copyright file="ApplicationInfo.cs" company="bda">
// 用户:mokeyish
// 日期:2016/10/20
// 时间:16:52
// </copyright>
// ------------------------------------------------------------------------------------------------
#endregion using System;
using Microsoft.Win32; namespace RegistryHelp
{
/// <summary>
/// 应用程序信息
/// </summary>
[RegistryRoot(Name = "RegistryHelp")]
public class ApplicationInfo:IRegistry
{
[RegistryMember(Name = "Path")]
private string _path; [RegistryMember(Name = "Server")]
private readonly string _server; [RegistryMember(Name = "Descirption")]
private string _descirption; private bool _isChanged; /// <summary>
/// 获取应用程序信息单例
/// </summary>
public static readonly ApplicationInfo Instance = new ApplicationInfo(); private ApplicationInfo()
{
this._path = AppDomain.CurrentDomain.BaseDirectory;
this._server = string.Empty;
AppDomain.CurrentDomain.ProcessExit += this.CurrentDomain_ProcessExit;
this._descirption = "注册表描述";
this._isChanged = !this.Read();
this._isChanged = !this.Save();
} private void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
this.Save();
} /// <summary>
/// 应用程序目录
/// </summary>
public string Path
{
get { return this._path; }
set
{
if (this._path==value)return;
this._isChanged = true;
this._path = value;
}
} /// <summary>
/// 服务器地址
/// </summary>
public string Server => this._server; /// <summary>
/// 描述
/// </summary>
public string Descirption
{
get { return this._descirption; }
set
{
if (this._descirption == value) return;
this._isChanged = true;
this._descirption = value;
}
} private bool Read()
{
RegistryKey registry = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32);
using (registry)
{
RegistryKey baseKey = registry.OpenSubKey("SOFTWARE");
using (baseKey) return this.Read(baseKey);
}
} private bool Save()
{
if (!this._isChanged) return false;
RegistryKey registry = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, Environment.Is64BitOperatingSystem
? RegistryView.Registry64
: RegistryView.Registry32);
using (registry)
{
RegistryKey baseKey = registry.CreateSubKey("SOFTWARE");
using (baseKey) return this.Save(baseKey);
}
}
}
}
已封装完善的对象类
#region summary // ------------------------------------------------------------------------------------------------
// <copyright file="IRegistry.cs" company="bda">
// 用户:mokeyish
// 日期:2016/10/15
// 时间:13:26
// </copyright>
// ------------------------------------------------------------------------------------------------ #endregion using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Win32; namespace RegistryHelp
{
/// <summary>
/// 可用于注册表快捷保存读取的接口
/// </summary>
public interface IRegistry
{
} /// <summary>
/// RegistryExitensionMethods
/// </summary>
public static class RegistryExitensionMethods
{
private static readonly Type IgnoreAttribute = typeof(RegistryIgnoreAttribute);
private static readonly Type MemberAttribute = typeof(RegistryMemberAttribute);
private static readonly Type RegistryInterface = typeof(IRegistry); /// <summary>
/// 读取注册表
/// </summary>
/// <param name="rootKey"></param>
/// <param name="registry"></param>
/// <param name="name"></param>
/// <exception cref="ArgumentNullException">registry is null</exception>
/// <exception cref="Exception">Member type is same with class type.</exception>
public static bool Read(this RegistryKey rootKey, IRegistry registry, string name = null)
{
if (registry == null) throw new ArgumentNullException(nameof(registry)); rootKey = rootKey?.OpenSubKey(name ?? registry.GetRegistryRootName()); if (rootKey == null) return false; bool flag = true;
using (rootKey)
{
Tuple<PropertyInfo[], FieldInfo[]> members = registry.GetMembers(); if (members.Item1.Length + members.Item2.Length == ) return false; foreach (PropertyInfo property in members.Item1)
{
string registryName = property.GetRegistryName();
object value;
if (RegistryInterface.IsAssignableFrom(property.PropertyType))
{
if (property.PropertyType == registry.GetType())
{
throw new Exception("Member type is same with Class type.");
} object oldvalue = property.GetValue(registry, null);
value = oldvalue ?? Activator.CreateInstance(property.PropertyType);
if (!rootKey.Read((IRegistry) value, registryName)) value = null;
}
else
{
value = rootKey.GetValue(registryName);
} if (value != null)
{
property.SetValue(registry, ChangeType(value, property.PropertyType), null);
}
else
{
flag = false;
}
} foreach (FieldInfo fieldInfo in members.Item2)
{
string registryName = fieldInfo.GetRegistryName();
object value;
if (RegistryInterface.IsAssignableFrom(fieldInfo.FieldType))
{
if (fieldInfo.FieldType == registry.GetType())
{
throw new Exception("Member type is same with Class type.");
} value = fieldInfo.GetValue(registry) ?? Activator.CreateInstance(fieldInfo.FieldType);
rootKey.Read((IRegistry) value, registryName);
}
else
{
value = rootKey.GetValue(registryName);
} if (value != null)
{
fieldInfo.SetValue(registry, ChangeType(value, fieldInfo.FieldType));
}
else
{
flag = false;
}
}
}
return flag;
} /// <summary>
/// 保存到注册表
/// </summary>
/// <param name="rootKey"></param>
/// <param name="registry"></param>
/// <param name="name"></param>
/// <exception cref="ArgumentNullException">registry is null</exception>
/// <exception cref="Exception">Member type is same with Class type.</exception>
public static bool Save(this RegistryKey rootKey, IRegistry registry, string name = null)
{
if (registry == null) throw new ArgumentNullException(nameof(registry)); rootKey = rootKey?.CreateSubKey(name ?? registry.GetRegistryRootName()); if (rootKey == null) return false; using (rootKey)
{
Tuple<PropertyInfo[], FieldInfo[]> members = registry.GetMembers(); if (members.Item1.Length + members.Item2.Length == ) return false; foreach (PropertyInfo property in members.Item1)
{
string registryName = property.GetRegistryName();
object value = property.GetValue(registry, null);
if (RegistryInterface.IsAssignableFrom(property.PropertyType))
{
if (property.PropertyType == registry.GetType())
{
throw new Exception("Member type is same with Class type.");
} if (value != null) rootKey.Save((IRegistry) value, registryName);
}
else
{
value = ChangeType(value, TypeCode.String);
if (value != null) rootKey.SetValue(registryName, value, RegistryValueKind.String);
} } foreach (FieldInfo fieldInfo in members.Item2)
{
string registryName = fieldInfo.GetRegistryName();
object value = fieldInfo.GetValue(registry);
if (RegistryInterface.IsAssignableFrom(fieldInfo.FieldType))
{
if (fieldInfo.FieldType == registry.GetType())
{
throw new Exception("Member type is same with Class type.");
} if (value != null) rootKey.Save((IRegistry) value, registryName);
}
else
{
value = ChangeType(value, TypeCode.String);
if (value != null) rootKey.SetValue(registryName, value, RegistryValueKind.String);
}
}
}
return true;
} /// <summary>
/// 读取注册表
/// </summary>
/// <param name="registry"></param>
/// <param name="rootKey"></param>
/// <param name="name"></param>
/// <exception cref="ArgumentNullException">registry is null</exception>
/// <exception cref="Exception">Member type is same with class type.</exception>
public static bool Read(this IRegistry registry, RegistryKey rootKey, string name = null)
{
return rootKey.Read(registry, name);
} /// <summary>
/// 保存到注册表
/// </summary>
/// <param name="registry"></param>
/// <param name="rootKey"></param>
/// <param name="name"></param>
/// <exception cref="ArgumentNullException">registry is null</exception>
/// <exception cref="Exception">Member type is same with class type.</exception>
public static bool Save(this IRegistry registry, RegistryKey rootKey, string name = null)
{
return rootKey.Save(registry, name);
} private static object ChangeType(object value, Type conversionType)
{
try
{
if (conversionType == RegistryInterface)
{
return value;
} if (conversionType == typeof(Guid))
{
return new Guid((string) value);
} if (conversionType.IsEnum)
{
return Enum.Parse(conversionType, (string) value);
} return Convert.ChangeType(value, conversionType); }
catch (Exception)
{
return null;
}
} private static object ChangeType(object value, TypeCode typeCode)
{
try
{ if (value is IConvertible) return Convert.ChangeType(value, typeCode);
return value.ToString();
}
catch (Exception)
{
return null;
}
} private static bool IsDefinedRegistryAttribute(this MemberInfo memberInfo)
{
return memberInfo.IsDefined(IgnoreAttribute, false) || memberInfo.IsDefined(MemberAttribute, false);
} private static string GetRegistryRootName(this IRegistry registry)
{
Type rootType = registry.GetType();
return rootType.IsDefined(typeof(RegistryRootAttribute), false)
? rootType.GetCustomAttribute<RegistryRootAttribute>().Name
: rootType.Name;
} private static string GetRegistryName(this MemberInfo memberInfo)
{
return memberInfo.IsDefined(MemberAttribute, false)
? memberInfo.GetCustomAttribute<RegistryMemberAttribute>().Name
: memberInfo.Name;
} private static Tuple<PropertyInfo[], FieldInfo[]> GetMembers(this IRegistry registry)
{
if (registry == null) throw new ArgumentNullException(nameof(registry));
Type t = registry.GetType(); IList<MemberInfo> lst =
t.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField |
BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty).ToList(); bool isDefinedAttribute = lst.Any(i => i.IsDefinedRegistryAttribute());
if (isDefinedAttribute)
{
lst = lst.Where(i => i.IsDefinedRegistryAttribute()).ToList();
}
return isDefinedAttribute
? new Tuple<PropertyInfo[], FieldInfo[]>(lst.OfType<PropertyInfo>().ToArray(),
lst.OfType<FieldInfo>().ToArray())
: new Tuple<PropertyInfo[], FieldInfo[]>(t.GetProperties(), t.GetFields());
} /// <summary>
/// The get custom attribute.
/// </summary>
/// <param name="element">
/// The element.
/// </param>
/// <typeparam name="T">Attribute type
/// </typeparam>
/// <returns>
/// The custom attribute
/// </returns>
private static T GetCustomAttribute<T>(this MemberInfo element) where T : Attribute
{
return (T)Attribute.GetCustomAttribute(element, typeof(T));
}
} /// <summary>
/// RegistryRootAttribute:用于描述注册表对象类
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class RegistryRootAttribute : Attribute
{
/// <summary>
/// Name
/// </summary>
public string Name { get; set; } /// <summary>
/// Value
/// </summary>
public string Value { get; set; }
} /// <summary>
/// RegistryIgnoreAttribute:忽略注册表成员,使用了该特性,将忽略未定义RegistryMemberAttribute的成员
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class RegistryIgnoreAttribute : Attribute { } /// <summary>
/// RegistryMemberAttribute:用于描述注册表成员,使用了该特性,将忽略未定义RegistryMemberAttribute的成员
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class RegistryMemberAttribute : Attribute
{
/// <summary>
/// Name
/// </summary>
public string Name { get; set; }
}
}
注册表对象映射实现类
c#注册表对象映射的更多相关文章
- MyBitis(iBitis)系列随笔之二:类型别名(typeAliases)与表-对象映射(ORM)
类型别名(typeAliases): 作用:通过一个简单的别名来表示一个冗长的类型,这样可以降低复杂度. 类型别名标签typeAliases中可以包含多个typeAlias,如下 < ...
- 10#Windows注册表的那些事儿
引言 用了多年的Windows系统,其实并没有对Windows系统进行过深入的了解,也正是由于Windows系统不用深入了解就可以简单上手所以才有这么多人去使用.笔者是做软件开发的,使用的基本都是Wi ...
- asp.net中通过注册表来检测是否安装Office(迅雷/QQ是否已安装)
原文 asp.net中通过注册表来检测是否安装Office(迅雷/QQ是否已安装) 检测Office是否安装以及获取安装 路径 及安装版本 代码如下 复制代码 #region 检测Office是否 ...
- Delphi的注册表操作
转帖:Delphi的注册表操作 2009-12-21 11:12:52 分类: Delphi的注册表操作 32位Delphi程序中可利用TRegistry对象来存取注册表文件中的信息. 一.创 ...
- 贴一份用delphi修改注册表改网卡MAC地址的代码
//提示:此代码需要use Registry, Common; function WriteMAC(model:integer):integer; var reg:TRegistry; begin r ...
- 【API】注册表编程基础-RegCreateKeyEx、RegSetValueEx
1.环境: 操作系统:Windows 10 x64 编译器:VS2015 2.关键函数 LONG WINAPI RegCreateKeyEx( _In_ HKEY hKey, _In_ LPCTSTR ...
- Win 通过修改注册表把CapsLock映射为Rshift
成品: REGEDIT4 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout] "Scancod ...
- ArcGIS AddIN开发之COM对象写入注册表
做一个交互式绘制文字的工具,希望这次设置的Symbol,下次打开ArcMap时自动调用这个Symbol,并支持对其进行修改. 解决方法是将这个Symbol写入注册表中,每次自动读取上一次设置的Symb ...
- 通过修改注册表将右alt键映射为application键
通过修改注册表将右alt键映射为application键的方法有许多键盘没有APPLICATION(上下文菜单)键,本文将教您如何把右ALT键映射为apps键.1.映射请将以下注册表信息用记事本保存为 ...
随机推荐
- js-异常处理语句
程序运行过程中难免会出错,出错后的运行结果往往是不正确的,因此运行时出错的程序通常被强制中止.运行时的错误统称为异常,为了能在错误发生时得到一个处理的机会,JavaScript提供了异常处理语句.包含 ...
- 叨叨PS那些活
临睡前记得今天技术小结没写...就起来叨叨些使用Photoshop做网站的活吧. 一般网站的建站流程和人员配置是: 1 美工,创建页面的psd图 2 前端工程师,根据psd图,切出html页面 3 后 ...
- Github教程(2)
一些小技巧: 在Github的个人主页中按Shift+/ 可以显示快捷键的操作: 在某个项目的文件列表中,按下t,即可根据输入的文件名和部分文件名查找文件: 对比两个分支之间的差别,以mybatis项 ...
- PowerDesigner的安装和数据库创建(转载)
此文描述详细,特此转载,仅复制了大部分内容,可参考原文CodeSmith和PowerDesigner的安装和数据库创建(原创) 请大家不要用于商业用途哈,要支持正版,大家都是做软件的,知道开发一套软件 ...
- JavaScrip的DOM操作
1.DOM的基本概念 DOM是文档对象模型,这种模型为树模型,文档是指标签文档:对象是指文档中每个元素:模型是指抽象化的东西 2.Windows对象操作 一.属性和方法 二.Window.open(& ...
- 一些JavaScript题目
在JavaScript中,运行下面代码,sum的值是(). var sum=0;for(i=1;i<10;i++){if(i%5==0)break;sum=sum+i;} A. 40B. 50C ...
- 2 Orchard汉化资源包的使用
Orchard安装完毕之后我们就可以在后台尝试做一些基本的操作感受下Orchard提供的一些功能,比如添加一个页面.菜单.文章什么的.也可以试着新建一些部件.布局之类的感受下.个人建议摆弄一下了解下就 ...
- Linux Shell系列教程之(十二)Shell until循环
本文是Linux Shell系列教程的第(十二)篇,更多Linux Shell教程请看:Linux Shell系列教程 在上两篇文章Linux Shell系列教程之(十)Shell for循环和Lin ...
- SQL数据库基础(六)
子查询,又叫做嵌套查询. 将一个查询语句做为一个结果集供其他SQL语句使用,就像使用普通的表一样,被当作结果集的查询语句被称为子查询. 子查询有两种类型: 一种是只返回一个单值的子查询,这时它可以用在 ...
- C# Out 传值
public void Out(out int a, out int b) {//out相当于return返回值 //可以返回多个值 //拿过来变量名的时候,里面默认为空值 a=1; b=2; } s ...