【C#】.ini文件读写

/// <summary>
/// 读配置文件方法的6个参数:所在的分区(section)、 键值、     初始缺省值、   StringBuilder、  参数长度上限 、配置文件路径
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <param name="retVal"></param>
/// <param name="size"></param>
/// <param name="filePath"></param>
/// <returns></returns>
[DllImport("kernel32")]
public static extern long GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder retVal, int size, string filePath);

/// <summary>
/// 写入配置文件方法的4个参数:  所在的分区(section)、  键值、     参数值、       配置文件路径
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="filePath"></param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);


/// <summary>
/// 读配置文件信息
/// </summary>
/// <param name="section">节点</param>
/// <param name="key">key值</param>
/// <returns></returns>
public static string GetFileIniValue(string section, string key,string FilePath)
{
    try
    {
        if (File.Exists(FilePath))  //检查是否有配置文件,并且配置文件内是否有相关数据。
        {
            StringBuilder sb = new StringBuilder(255);
            GetPrivateProfileString(section, key, "配置文件不存在,读取未成功!", sb, 255, FilePath);

            return sb.ToString();
        }
    }
    catch (Exception ex)
    {
      
    }
    return string.Empty;
}


/// <summary>
/// 写INI配置文件
/// </summary>
/// <param name="section">节点</param>
/// <param name="key">key值</param>
/// <param name="value">值</param>
public static bool SetFileIniValue(string section, string key, string value, string FilePath)
{
    bool bRet;
    try
    {
        bRet = WritePrivateProfileString(section, key, value, FilePath) > 0;
    }
    catch (Exception ex)
    {
        bRet = false;
    }
    return bRet;
}
posted @ 2024-09-25 14:57  qiutian-hao  阅读(65)  评论(0编辑  收藏  举报