调用方法:
int ibaudrate = inihelper.readconfig(com_setup, 波特率)
inihelper类:
public class inihelper
{
private static string filename = application.startuppath + \\appconfig.ini;
///
/// 读取配置文件
///
///
///
///
///
public static t readconfig(string section, string key)
{
if (file.exists(filename))
{
inifile f = new inifile(filename);
string value = f.readcontentvalue(section, key);
if (string.isnullorwhitespace(value))
return default(t);
if (typeof(t).isenum)
return (t)enum.parse(typeof(t), value, true);
return (t)convert.changetype(value, typeof(t));
}
else
{
return default(t);
}
}
///
/// 写配置文件
///
///
///
///
public static void writeconfig(string section, string key, string value)
{
//如果文件不存在,则创建
if (!file.exists(filename))
{
using (filestream myfs = new filestream(filename, filemode.create)) { }
}
inifile f = new inifile(filename);
f.writecontentvalue(section, key, value);
}
}
核心代码:
public class inifile
{
public string path;
public inifile(string path)
{
this.path = path;
}
///
/// 写入ini文件
///
/// 节点名称[如[typename]]
/// 键
/// 值
/// 文件路径
///
[dllimport(kernel32)]
private static extern long writeprivateprofilestring(string section, string key, string val, string filepath);
///
/// 读取ini文件
///
/// 节点名称
/// 键
/// 值
/// stringbulider对象
/// 字节大小
/// 文件路径
///
[dllimport(kernel32)]
private static extern int getprivateprofilestring(string section, string key, string def, stringbuilder retval, int size, string filepath);
///
/// 写入
///
///
///
///
public void writecontentvalue(string section, string key, string ivalue)
{
writeprivateprofilestring(section, key, ivalue, this.path);
}
///
/// 读取ini文件中的内容方法
///
/// 键
/// 值
///
public string readcontentvalue(string section, string key)
{
stringbuilder temp = new stringbuilder(1024);
getprivateprofilestring(section, key, , temp, 1024, this.path);
return temp.tostring();
}
}