Skip to content

Instantly share code, notes, and snippets.

@viko16
Last active December 20, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viko16/6200290 to your computer and use it in GitHub Desktop.
Save viko16/6200290 to your computer and use it in GitHub Desktop.
C# ini编辑类
class INIClass
{
public string inipath;
[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);
/// <summary>
/// 构造方法
/// </summary>
/// <param name="INIPath">文件路径</param>
public INIClass(string INIPath)
{
inipath = INIPath;
}
/// <summary>
/// 写入INI文件
/// </summary>
/// <param name="Section">分组名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
/// <param name="Value">值</param>
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.inipath);
}
/// <summary>
/// 读出INI文件
/// </summary>
/// <param name="Section">分组名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(500);
/*if (GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath) != 0) { return temp.ToString(); }
else { throw new Exception("读取配置失败"); return ""; }*/
if (!File.Exists(inipath))
{
throw new Exception("找不到这个文件。");
}
else if (GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath) == 0)
{
throw new Exception(Key + "不存在。");
}
return temp.ToString();
}
/// <summary>
/// 验证文件是否存在
/// </summary>
/// <returns>布尔值</returns>
public bool ExistINIFile()
{
return File.Exists(inipath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment