Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

C# Microsoft.Extensions.Configuration.Ini で INI ファイルを読み込む

0
Posted at

はじめに

Microsoft.Extensions.Configuration.Ini で INI ファイルの読込クラスを作ります。

改訂履歴

  • 2026/06/14 : 初版公開。

本文

1. 環境

  • Visual Studio Community 2022
  • .NET 8.0
  • Microsoft.Extensions.Configuration.Binder 10.0.9
  • Microsoft.Extensions.Configuration.Ini 10.0.9

2. ソース

サンプルの INI ファイルです。

IniExampleNet8.ini
; ---------------------------
; アプリケーション
; ---------------------------
[App]
AppName=IniExampleNet8
IsDebugMode=false

; ---------------------------
; データベース
; ---------------------------
[Database]
DataSource=localhost
Port=1433
UserId=Admin
Password=Admin1234

IniFile クラスに INI ファイルの設定値を格納します。

IniFile.cs
using Microsoft.Extensions.Configuration;

namespace IniExampleNet8
{
    /// <summary>
    /// INI ファイルを表します。
    /// </summary>
    public class IniFile
    {
        /// <summary>
        /// App セクションを表します。
        /// </summary>
        public AppSection App { get; set; } = new();

        /// <summary>
        /// Database セクションを表します。
        /// </summary>
        public DatabaseSection Database { get; set; } = new();
    }

    /// <summary>
    /// INI ファイルの App セクションを表します。
    /// </summary>
    public class AppSection
    {
        /// <summary>
        /// AppName キーを表します。
        /// </summary>
        public string AppName { get; set; } = string.Empty;

        /// <summary>
        /// IsDebugMode キーを表します。
        /// </summary>
        public bool IsDebugMode { get; set; }
    }

    /// <summary>
    /// INI ファイルの Database セクションを表します。
    /// </summary>
    public class DatabaseSection
    {
        /// <summary>
        /// DataSource キーを表します。
        /// </summary>
        public string DataSource { get; set; } = string.Empty;

        /// <summary>
        /// Port キーを表します。
        /// </summary>
        public int Port { get; set; }

        /// <summary>
        /// UserId キーを表します。
        /// </summary>
        public string UserId { get; set; } = string.Empty;

        /// <summary>
        /// Password キーを表します。
        /// </summary>
        public string Password { get; set; } = string.Empty;
    }
}

IniFileLoader で IniFile クラスのインスタンスを生成します。Microsoft.Extensions.Configuration.Ini では ConfigurationBinder.Get() による自動マッピングも可能ですが、設定値が不正な場合にどの項目でエラーが発生したのかを分かりやすくするため、本記事では各項目を一つずつ手動で設定しています

IniFileLoader.cs
using Microsoft.Extensions.Configuration;

namespace IniExampleNet8;

/// <summary>
/// INI ファイルの読込を行います。
/// </summary>
public static class IniFileLoader
{
    private static readonly string s_iniFileName = "IniExampleNet8.ini";

    /// <summary>
    /// INI ファイルを読み込み、新しい <see cref="IniFile"/> インスタンスを生成します。
    /// </summary>
    /// <returns>生成した <see cref="IniFile"/>。</returns>
    /// <exception cref="FileNotFoundException">INI ファイルが見つからない場合。</exception>
    /// <exception cref="InvalidOperationException">設定項目が未設定、または設定値が不正な場合。</exception>
    public static IniFile Create()
    {
        // INI ファイルの存在チェックを行います。
        var filePath = Path.Combine(AppContext.BaseDirectory, s_iniFileName);
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException($"INI ファイル '{filePath}' が見つかりません。", filePath);
        }

        // INI ファイルを読み込みます。
        IConfiguration configuration = new ConfigurationBuilder()
            .AddIniFile(filePath, optional: false, reloadOnChange: false)
            .Build();

        // App セクションの設定値を取得します。
        var app = new AppSection
        {
            AppName = GetRequiredString(
                configuration,
                Key(nameof(IniFile.App), nameof(AppSection.AppName))),

            IsDebugMode = GetRequiredBool(
                configuration,
                Key(nameof(IniFile.App), nameof(AppSection.IsDebugMode)))
        };

        // Database セクションの設定値を取得します。
        var database = new DatabaseSection
        {
            DataSource = GetRequiredString(
                configuration,
                Key(nameof(IniFile.Database), nameof(DatabaseSection.DataSource))),

            Port = GetRequiredInt(
                configuration,
                Key(nameof(IniFile.Database), nameof(DatabaseSection.Port))),

            UserId = GetRequiredString(
                configuration,
                Key(nameof(IniFile.Database), nameof(DatabaseSection.UserId))),

            Password = GetRequiredString(
                configuration,
                Key(nameof(IniFile.Database), nameof(DatabaseSection.Password)))
        };

        // IniFile インスタンスを生成して返します。
        return new IniFile
        {
            App = app,
            Database = database,
        };
    }

    /// <summary>
    /// 設定キーを生成します。
    /// </summary>
    /// <param name="section">セクション名。</param>
    /// <param name="key">キー名。</param>
    /// <returns>設定キー。</returns>
    private static string Key(string section, string key) => $"{section}:{key}";

    /// <summary>
    /// 必須の文字列を取得します。
    /// </summary>
    /// <param name="configuration"><see cref="IConfiguration"/> インスタンス。</param>
    /// <param name="key">設定キー。</param>
    /// <returns>設定値。</returns>
    /// <exception cref="InvalidOperationException">設定項目が未設定、または設定値が不正な場合。</exception>
    private static string GetRequiredString(IConfiguration configuration, string key)
    {
        var value = configuration[key];

        if (string.IsNullOrWhiteSpace(value))
        {
            throw new InvalidOperationException($"項目 '{key}' が未設定です。");
        }

        return value;
    }

    /// <summary>
    /// 必須の整数を取得します。
    /// </summary>
    /// <param name="configuration"><see cref="IConfiguration"/> インスタンス。</param>
    /// <param name="key">設定キー。</param>
    /// <returns>設定値。</returns>
    /// <exception cref="InvalidOperationException">設定項目が未設定、または設定値が不正な場合。</exception>
    private static int GetRequiredInt(IConfiguration configuration, string key)
    {
        var value = configuration[key];

        if (string.IsNullOrWhiteSpace(value))
        {
            throw new InvalidOperationException($"項目 '{key}' が未設定です。");
        }

        if (!int.TryParse(value, out var result))
        {
            throw new InvalidOperationException($"項目 '{key}' の値 '{value}' が整数ではありません。");
        }

        return result;
    }

    /// <summary>
    /// 必須のブール値を取得します。
    /// </summary>
    /// <param name="configuration"><see cref="IConfiguration"/> インスタンス。</param>
    /// <param name="key">設定キー。</param>
    /// <returns>設定値。</returns>
    /// <exception cref="InvalidOperationException">設定項目が未設定、または設定値が不正な場合。</exception>
    private static bool GetRequiredBool(IConfiguration configuration, string key)
    {
        var value = configuration[key];

        if (string.IsNullOrWhiteSpace(value))
        {
            throw new InvalidOperationException($"項目 '{key}' が未設定です。");
        }

        if (!bool.TryParse(value, out var result))
        {
            throw new InvalidOperationException($"項目 '{key}' の値 '{value}' には true または false を指定してください。");
        }

        return result;
    }
}

とりあえず Program.cs で読込します。

Program.cs
namespace IniExampleNet8;

/// <summary>
/// アプリケーションのエントリーポイントを定義します。
/// </summary>
internal static class Program
{
    /// <summary>
    /// アプリケーションのメインエントリポイントです。
    /// </summary>
    [STAThread]
    internal static void Main()
    {
        ApplicationConfiguration.Initialize();

        try
        {
            // INI ファイルを読込する。
            IniFile iniFile = IniFileLoader.Create();
        }
        catch (Exception ex) when (
            ex is FileNotFoundException ||
            ex is InvalidOperationException)
        {
            MessageBox.Show("INI ファイルの読込に失敗しました。" + ex.Message);
            return;
        }
        catch (Exception ex)
        {
            MessageBox.Show("予期しないエラーが発生しました。" + ex.ToString());
            return;
        }

        Application.Run(new Form1());
    }
}

おわりに

なお Microsoft.Extensions.Configuration.Ini には、書込機能はありません。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?