C# Winform 调用系统接口操作 INI 配置文件的代码
更新时间:2011年05月14日 16:00:44 作者:
封装了一小段代码, 调用系统接口, 操作配置文件. 一般用于 .ini 文件, 或者其它键值对格式的配置文件
包括了写入和读取功能. 写入的时候, 如果文件不存在会自动创建. 如果对应的键已经存在, 则自动覆盖它的值. 读取的时候, 如果对应的文件不存在, 或者键名不存在, 则返回一个 empty 值. 非常方便 ^_^
// 系统接口类
public static class WinAPI
{
[DllImport("kernel32")] // 写入配置文件的接口
private static extern long WritePrivateProfileString(
string section, string key, string val, string filePath);
[DllImport("kernel32")] // 读取配置文件的接口
private static extern int GetPrivateProfileString(
string section, string key, string def,
StringBuilder retVal, int size, string filePath);
// 向配置文件写入值
public static void ProfileWriteValue(
string section, string key, string value, string path)
{
WritePrivateProfileString(section, key, value, path);
}
// 读取配置文件的值
public static string ProfileReadValue(
string section, string key, string path)
{
StringBuilder sb = new StringBuilder(255);
GetPrivateProfileString(section, key, "", sb, 255, path);
return sb.ToString().Trim();
}
}
复制代码 代码如下:
// 系统接口类
public static class WinAPI
{
[DllImport("kernel32")] // 写入配置文件的接口
private static extern long WritePrivateProfileString(
string section, string key, string val, string filePath);
[DllImport("kernel32")] // 读取配置文件的接口
private static extern int GetPrivateProfileString(
string section, string key, string def,
StringBuilder retVal, int size, string filePath);
// 向配置文件写入值
public static void ProfileWriteValue(
string section, string key, string value, string path)
{
WritePrivateProfileString(section, key, value, path);
}
// 读取配置文件的值
public static string ProfileReadValue(
string section, string key, string path)
{
StringBuilder sb = new StringBuilder(255);
GetPrivateProfileString(section, key, "", sb, 255, path);
return sb.ToString().Trim();
}
}
相关文章
C#实现导出List数据到xml文件的方法【附demo源码下载】
这篇文章主要介绍了C#实现导出List数据到xml文件的方法,涉及C#针对list类及xml文件的相关操作技巧,并附带完整demo源码供读者下载参考,需要的朋友可以参考下2016-08-08
C# Environment.CurrentDirectory 静态属性的实现
本文主要介绍了C# Environment.CurrentDirectory 静态属性的实现,它返回当前应用程序的工作目录路径,具有一定的参考价值,感兴趣的可以了解一下2024-02-02


最新评论