using System;
|
using System.Reflection;
|
using System.Runtime.InteropServices;
|
using System.Text;
|
|
namespace XImaging.Automation.Library.HxDriverLib
|
{
|
/// <summary>
|
/// INI文件读写类
|
/// </summary>
|
public class IniHelper
|
{
|
#region API函数声明
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] //返回0表示失败,非0为成功
|
private static extern bool WritePrivateProfileString(string section, string key,
|
string val, string filePath);
|
|
[DllImport("kernel32.dll", CharSet = CharSet.Auto)] //返回取得字符串缓冲区的长度
|
private static extern uint GetPrivateProfileString(string section, string key,
|
string def, StringBuilder retVal, int size, string filePath);
|
|
#endregion
|
|
#region 封装
|
|
/// <summary>
|
/// 从INI文件读取值
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="iniFile"></param>
|
/// <param name="section"></param>
|
/// <param name="key"></param>
|
/// <param name="defaultValue"></param>
|
/// <returns></returns>
|
public static T IniGetValue<T>(string iniFile, string section, string key, T defaultValue = default(T))
|
{
|
if (string.IsNullOrEmpty(section))
|
{
|
LogConstant.logger.Print("未指定节点名称(Section)");
|
return defaultValue;
|
}
|
if (string.IsNullOrEmpty(key))
|
{
|
LogConstant.logger.Print("未指定节点名称(Key)");
|
return defaultValue;
|
}
|
|
string strValue = defaultValue.ToString(); ;
|
const int SIZE = 1024 * 10;
|
|
|
StringBuilder sb = new StringBuilder(SIZE);
|
uint bytesReturned = GetPrivateProfileString(section, key, defaultValue.ToString(), sb, SIZE, iniFile);
|
|
if (bytesReturned != 0)
|
strValue = sb.ToString();
|
sb = null;
|
|
Type t = typeof(T);
|
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) //支持可空类型
|
t = t.GetGenericArguments()[0];
|
|
var tryParse = t.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder
|
, new Type[] { strValue.GetType(), t.MakeByRefType() }
|
, new ParameterModifier[] { new ParameterModifier(2) });
|
|
if (tryParse != null)
|
{
|
var parameters = new object[] { strValue, Activator.CreateInstance(t) };
|
bool success = (bool)tryParse.Invoke(null, parameters);
|
if (success)
|
return (T)parameters[1];
|
else
|
return defaultValue;
|
}
|
|
return (T)Convert.ChangeType(strValue, typeof(T));
|
}
|
|
/// <summary>
|
/// 向INI文件写值
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="iniFile"></param>
|
/// <param name="section"></param>
|
/// <param name="key"></param>
|
/// <param name="value"></param>
|
/// <returns></returns>
|
public static bool IniWriteValue<T>(string iniFile, string section, string key, T value)
|
{
|
if (string.IsNullOrEmpty(section))
|
{
|
LogConstant.logger.Print("未指定节点名称(Section)");
|
return false;
|
}
|
if (string.IsNullOrEmpty(key))
|
{
|
LogConstant.logger.Print("未指定节点名称(Key)");
|
return false;
|
}
|
|
return WritePrivateProfileString(section, key, value.ToString(), iniFile);
|
}
|
|
#endregion
|
}
|
}
|