.ini文件处理帮助类
一、定义Class
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace IniDemo
{
public class IniFile
{
private string m_FileName;
public string FileName
{
get
{
return this.m_FileName;
}
set
{
this.m_FileName = value;
}
}
[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileInt(string lpAppName, string lpKeyName, int nDefault, string lpFileName);
[DllImport("kernel32.dll")]
private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);
[DllImport("kernel32.dll")]
private static extern int WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);
public IniFile(string aFileName)
{
this.m_FileName = aFileName;
}
public IniFile()
{
}
public int ReadInt(string section, string name, int def)
{
return IniFile.GetPrivateProfileInt(section, name, def, this.m_FileName);
}
public string ReadString(string section, string name, string def)
{
StringBuilder stringBuilder = new StringBuilder(2048);
IniFile.GetPrivateProfileString(section, name, def, stringBuilder, 2048, this.m_FileName);
return stringBuilder.ToString();
}
public void WriteInt(string section, string name, int Ival)
{
IniFile.WritePrivateProfileString(section, name, Ival.ToString(), this.m_FileName);
}
public void WriteString(string section, string name, string strVal)
{
IniFile.WritePrivateProfileString(section, name, strVal, this.m_FileName);
}
public void DeleteSection(string section)
{
IniFile.WritePrivateProfileString(section, null, null, this.m_FileName);
}
public void DeleteAllSection()
{
IniFile.WritePrivateProfileString(null, null, null, this.m_FileName);
}
public string IniReadValue(string section, string name)
{
StringBuilder stringBuilder = new StringBuilder(256);
IniFile.GetPrivateProfileString(section, name, "", stringBuilder, 256, this.m_FileName);
return stringBuilder.ToString();
}
public void IniWriteValue(string section, string name, string value)
{
IniFile.WritePrivateProfileString(section, name, value, this.m_FileName);
}
}
}
二、调用方法
IniFile iniFile = new IniFile(Environment.CurrentDirectory + "\\LocalInf.ini");
//读取Local节点下M的值,默认为空值
string m = iniFile.ReadString("Local", "M", "");
//Local节点下写F=f
iniFile.WriteString("Local", "F", "f");
//读取Local节点下IsSleep的字符串值,并转为bool类型值,给出默认值为False
bool f = bool.Parse(iniFile.ReadString("Local", "IsSleep", "False"));
//读取Local节点下的C的字符串值,并转为double类型值,给出默认值0
bool f = double.Parse(iniFile.ReadString("Local", "C", "0"));
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15618356.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。
