C# INI配置帮助类

一、调用动态库

private string fileName;
[DllImport("kernel32")]
private static extern int GetPrivateProfileInt(
 string lpAppName,// 指向包含 Section 名称的字符串地址
      string lpKeyName,// 指向包含 Key 名称的字符串地址
      int nDefault,// 如果 Key 值没有找到,则返回缺省的值是多少
      string lpFileName
 );

[DllImport("kernel32")]
private static extern int GetPrivateProfileString(
 string lpAppName,// 指向包含 Section 名称的字符串地址
      string lpKeyName,// 指向包含 Key 名称的字符串地址
      string lpDefault,// 如果 Key 值没有找到,则返回缺省的字符串的地址
      StringBuilder lpReturnedString,// 返回字符串的缓冲区地址
      int nSize,// 缓冲区的长度
      string lpFileName
 );

[DllImport("kernel32")]
private static extern bool WritePrivateProfileString(
 string lpAppName,// 指向包含 Section 名称的字符串地址
      string lpKeyName,// 指向包含 Key 名称的字符串地址
      string lpString,// 要写的字符串地址
      string lpFileName
 );

public IniUtil(string filename)
{
    fileName = filename;
}

二、接口实现

public int getInt(string section, string key, int def)
{
    return GetPrivateProfileInt(section, key, def, fileName);
}
public int getUint(string section, string key, int def)
{
    return GetPrivateProfileInt(section, key, def, fileName);
}
public string getString(string section, string key, string def)
{
    string result = string.Empty;
    try
    {
        StringBuilder temp = new StringBuilder(1024);
        GetPrivateProfileString(section, key, def, temp, 1024, fileName);
        if (temp.ToString().ToLower()!="null")
        {
            result = temp.ToString();
        }
        else
        {
            result = null;
        }
        
    }
    catch (System.Exception ex)
    {
        LoggerUtil.Error("IniUtil:getString", ex);
        result = null;
    }
    return result;
}
public void writeInt(string section, string key, int iVal)
{
    WritePrivateProfileString(section, key, iVal.ToString(), fileName);
}
public void writeString(string section, string key, string strVal)
{
    WritePrivateProfileString(section, key, strVal, fileName);
}
public void delKey(string section, string key)
{
    WritePrivateProfileString(section, key, null, fileName);
}
public void delSection(string section)
{
    WritePrivateProfileString(section, null, null, fileName);
}

三、调用方式

//获取文件
private static readonly IniUtil iniUtil = new IniUtil(Directory.GetCurrentDirectory() + "\\config.ini");
//调用方法
iniUtil.getInt("SystemSetting", "TimeoutDuration", 0)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值