调用方法:
int iBaudRate = InIHelper.ReadConfigInIHelper类:
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();
}
}










