使用C#讀寫ini檔案

xhubobo發表於2024-03-09

使用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
}

相關文章