使用C#读写ini文件
使用C#读写ini文件要用到Windows的API函数:GetPrivateProfileString、WritePrivateProfileString,下面对该方法进行封装并以具体ini文件为例说明如何读写。
1、ini文件示例
; FTP服务器参数 [FtpServer] IP=127.0.0.1 Port=21 UserName=user Password=user
2、IniHelper.cs
public static class IniHelper { [DllImport("kernel32", CharSet = CharSet.Unicode)] // ReSharper disable once UnusedMember.Local private static extern long WritePrivateProfileString(string section, string key, string value, string filePath); [DllImport("kernel32", CharSet = CharSet.Unicode)] private static extern int GetPrivateProfileString(string section, string key, string defaultValue, StringBuilder resultValue, int size, string filePath); public static string ReadStr(string section, string key, string defaultValue, string filePath) { var ret = new StringBuilder(255); GetPrivateProfileString(section, key, defaultValue, ret, ret.Capacity, filePath); return ret.ToString(); } public static int ReadInt(string section, string key, int defaultValue, string filePath) { var text = ReadStr(section, key, $"{defaultValue}", filePath); return int.TryParse(text, out var intValue) ? intValue : defaultValue; } public static void WriteValue(string section, string key, string value, string filePath) { WritePrivateProfileString(section, key, value, filePath); } }
3、IniConfigManager.cs
internal sealed class IniConfigManager { public string FtpIp { get; private set; } //FTP服务器IP public int FtpPort { get; private set; } //FTP服务器端口 public string FtpUserName { get; private set; } //FTP服务器用户名 public string FtpPassword { get; private set; } //FTP服务器密码 private readonly string _iniPath = Path.Combine(Application.StartupPath, "AppSettings.ini"); //ini配置文件路径 private readonly ILog _logger = LogManager.GetLogger(nameof(IniConfigManager)); /// <summary> /// 加载配置文件 /// </summary> public void LoadConfig() { try { //FTP服务器参数 FtpIp = IniHelper.ReadStr("FtpServer", "IP", "127.0.0.1", _iniPath); FtpPort = IniHelper.ReadInt("FtpServer", "Port", 21, _iniPath); FtpUserName = IniHelper.ReadStr("FtpServer", "UserName", "user", _iniPath); FtpPassword = IniHelper.ReadStr("FtpServer", "Password", "user", _iniPath); } catch (Exception e) { _logger.Error($@"加载ini配置文件失败:{e.Message}."); } } //设置STP服务器参数 public void SetFtpConfig(string ip, int port, string userName, string password) { FtpIp = ip; FtpPort = port; FtpUserName = userName; FtpPassword = password; try { IniHelper.WriteValue("FtpServer", "IP", ip, _iniPath); IniHelper.WriteValue("FtpServer", "Port", $"{port}", _iniPath); IniHelper.WriteValue("FtpServer", "UserName", userName, _iniPath); IniHelper.WriteValue("FtpServer", "Password", password, _iniPath); } catch (Exception e) { _logger.Error($@"设置STP服务器参数失败:{e.Message}."); throw; } } #region 单例模式 private static IniConfigManager _instance; private static readonly object LockInstanceHelper = new object(); private IniConfigManager() { } public static IniConfigManager Instance { get { if (_instance != null) { return _instance; } lock (LockInstanceHelper) { _instance = _instance ?? new IniConfigManager(); } return _instance; } } #endregion }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库