/// <summary>
/// 读写配置文件(并创建)
/// </summary>
public class FileConfig
{
#region 操作INI文件的API函数
[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);
#endregion
private readonly string _filePath;
/// <summary>
/// 读写配置文件(并创建)
/// </summary>
/// <param name="filePath">配置文件的存放路径(包含文件名)</param>
public FileConfig(string filePath)
{
_filePath = filePath;
}
/// <summary>
/// 将配置信息写入配置文件中(同部门同键值将被新值替代)
/// </summary>
/// <param name="departments">部门 例:【登陆信息】</param>
/// <param name="key">键 例:姓名=</param>
/// <param name="value">值 例:Administrator</param>
/// <returns>当写入成功时则返回字符串:0;当写入失败时则返回异常字符串</returns>
public string WriteProfile(string departments, string key, string value)
{
try
{
if (!File.Exists(_filePath))
{
File.Create(_filePath).Close();
}
WritePrivateProfileString(departments, key, value, _filePath);
return "0";
}
catch (Exception ex)
{
throw new Exception("写入时出错:" + ex.Message);
}
}
/// <summary>
/// 读取配置信息中内容(根据部门与键)
/// </summary>
/// <param name="departments">要提取值的部门</param>
/// <param name="key">要提取值的对应键</param>
/// <returns>当提去成功时则返回提取出来的值,否则返回空值null</returns>
public string ReadProfile(string departments, string key)
{
try
{
var reValue = new StringBuilder(255);
if (File.Exists(_filePath))
{
GetPrivateProfileString(departments, key, "", reValue, 255, _filePath);
return reValue.ToString();
}
return null;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
C# 读写配置文件
最新推荐文章于 2024-05-29 00:15:00 发布