1.对ini文件进行序列化和反序列化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
public class IniDeserialize<T> where T : class, new()
{
/// <summary>
/// 若ini文件中无对应值,就提取默认对象中的值
/// </summary>
T _defaultT;
/// <summary>
/// 序列化后的对象
/// </summary>
public T Value { get; set; }
IniRW _iniRW;
public IniDeserialize(string path, T defaultT)
{
_iniRW = new IniRW(path);
_defaultT = defaultT;
Deserialize();
}
/// <summary>
/// 反序列化
/// </summary>
/// <returns></returns>
bool Deserialize()
{
Value = new T();
Type tInfo = Value.GetType();
string section = tInfo.Name;
foreach (PropertyInfo p in tInfo.GetProperties())
{
string key = p.Name;
string iniValue = _iniRW.ReadString(section, key);
if (iniValue == string.Empty)
{
PropertyInfo pd = _defaultT.GetType().GetProperty(key);
iniValue = pd.GetValue(_defaultT, null) as string;
}
object value = iniValue.Format(p.PropertyType);
p.SetValue(Value, value, null);
}
return true;
}
/// <summary>
/// 序列化保存
/// </summary>
/// <returns></returns>
public bool Serialize()
{
Type tInfo = Value.GetType();
string section = tInfo.Name;
foreach (PropertyInfo p in tInfo.GetProperties())
{
string key = p.Name;
object value = p.GetValue(Value, null);
_iniRW.WriteValue(section, key, value);
}
return true;
}
}
2.对ini文件的读写
public class IniRW : IniUse
{
public string IniPath;
public IniRW(string path)
{
IniPath = path;
}
public virtual bool WriteValue(string section, string key, object value)
{
string v = value == null ? "" : value.ToString();
long ret = WritePrivateProfileString(section, key, v, IniPath);
return true;
}
public virtual string ReadString(string section, string key)
{
StringBuilder sb = new StringBuilder(255);
string def = string.Empty;
int ret = GetPrivateProfileString(section, key, def, sb, 255, IniPath);
return ret == 0 ? def : sb.ToString();
}
public int ReadInt(string section, string key)
{
return (int)ReadDouble(section, key);
}
public short ReadShort(string section, string key)
{
return (short)ReadDouble(section, key);
}
public byte ReadByte(string section, string key)
{
return (byte)ReadDouble(section, key);
}
public double ReadDouble(string section, string key)
{
double res = 0;
string sb = ReadString(section, key);
double.TryParse(sb, out res);
return res;
}
public bool ReadBool(string section, string key)
{
bool res = false;
string sb = ReadString(section, key).Trim();
if (sb == "1")
{
return true;
}
else if (sb == "0")
{
return false;
}
bool.TryParse(sb, out res);
return res;
}
}
3.调用 kernel32 对ini的读写
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices; //WinAPI引用命名空间
/// <summary>
/// 对ini配置文件读写,写时文件不存在会自动创建(不会自动创建文件夹)
/// </summary>
public class IniUse
{
[DllImport("kernel32")]
public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
/// <summary>
/// 从ini文件中获取键值 不存在则自动创建 若不存在键时返回def默认值,当不存在且def为空值时才返回0,否则为1 ps:文件打开的状态下都可以读取
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="def"></param>
/// <param name="retVal"></param>
/// <param name="size"></param>
/// <param name="filePath"></param>
/// <returns></returns>
[DllImport("kernel32")]
public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
}
4.将读取到的字符串转换为对应的类型
using System;
using System.ComponentModel;
/// <summary>
/// 将字符串格式化成指定的数据类型
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
public static object Format(this string str, Type type)
{
if (string.IsNullOrEmpty(str))
return null;
if (type == null)
return str;
if (type.IsArray)
{
Type elementType = type.GetElementType();
string[] strs = str.Split(new char[] { ';' });
Array array = Array.CreateInstance(elementType, strs.Length);
for (int i = 0, c = strs.Length; i < c; ++i)
{
array.SetValue(ConvertSimpleType(strs[i], elementType), i);
}
return array;
}
return ConvertSimpleType(str, type);
}
private static object ConvertSimpleType(object value, Type destinationType)
{
object returnValue;
if ((value == null) || destinationType.IsInstanceOfType(value))
{
return value;
}
string str = value as string;
if ((str != null) && (str.Length == 0))
{
return null;
}
TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
bool flag = converter.CanConvertFrom(value.GetType());
if (!flag)
{
converter = TypeDescriptor.GetConverter(value.GetType());
}
if (!flag && !converter.CanConvertTo(destinationType))
{
throw new InvalidOperationException("无法转换成类型:" + value.ToString() + "==>" + destinationType);
}
try
{
returnValue = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, destinationType);
}
catch (Exception e)
{
throw new InvalidOperationException("类型转换出错:" + value.ToString() + "==>" + destinationType, e);
}
return returnValue;
}
}