C#ini配置文件读写
using System;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace INIFile
{
class INI
{
#region API函数声明
[DllImport("kernel32")]//返回0表示失败,非0为成功
private static extern long WritePrivateProfileString(string section, string key,
string val, string filePath);
[DllImport("kernel32")]//返回取得字符串缓冲区的长度
private static extern long GetPrivateProfileString(string section, string key,
string def, StringBuilder retVal, int size, string filePath);
#endregion
#region 读Ini文件
/// <summary>
/// 读取配置
/// </summary>
/// <param name="iniFilePath">路径</param>
/// <param name="Section">键名</param>
/// <param name="Key">项名</param>
/// <param name="NoText">默认值</param>
/// <returns></returns>
public static string ReadIniData(string iniFilePath,string Section, string Key, string NoText)
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
if (temp.ToString().Length > 0)
{
return temp.ToString();
}
else
{
return NoText;
}
}
else
{
return NoText;
}
}
#endregion
#region 写Ini文件
/// <summary>
/// 写配置
/// </summary>
/// <param name="iniFilePath">路径</param>
/// <param name="Section">键名</param>
/// <param name="Key">项名</param>
/// <param name="Value">写入值</param>
/// <returns></returns>
public static bool WriteIniData(string iniFilePath,string Section, string Key, string Value)
{
if (File.Exists(iniFilePath))
{
long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
if (OpStation == 0)
{
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
#endregion
}
}
© 著作权归作者所有
文章评论(0)