【C#.NET解説】 app.configを操る、Configurationクラスの基本機能と活用方法

2024年12月14日土曜日

システム 基本 制御フロー

t f B! P L
C#.NET解説 Configurationクラスの基本機能と活用方法がよくわかるガイド
Configuration

名前空間 System.Configuration

自己紹介

私は死の領域を統べる者。普段は静寂と終焉をもたらすが、今日はプログラムにおける生命線とも言える「Configurationクラス」を解説しよう。このクラスはアプリケーションの設定を管理し、環境に応じた動的な動作を可能にする。使い方を知れば、開発者としての力を大いに高められるだろう。

基本機能

「Configurationクラス」はアプリケーション構成ファイル(たとえばsystem.config)を読み取るために使用される。このファイルに設定を保存することで、コードの柔軟性と再利用性を向上させることができる。

次に、基本的な使用例を示す。以下のようなsystem.configファイルが存在するものとする。

system.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="ApiEndpoint" value="https://api.example.com" />
    </appSettings>
</configuration>

この設定を読み取るコードは以下のようになる:

C#
using System;
using System.Configuration;

class Program
{
    static void Main()
    {
        // 設定値を取得
        string apiEndpoint = ConfigurationManager.AppSettings["ApiEndpoint"];
        Console.WriteLine($"APIエンドポイント: {apiEndpoint}");
    }
}

これにより、設定ファイルから値を取得し、コード内で利用できるようになる。

よく使う場面と注意点

Configurationクラスは、アプリケーションの設定を外部ファイルで管理したいときに便利だ。しかし、設定が正しく読み取れない場合やファイルが見つからない場合がある。その際には適切なエラーハンドリングを行う必要がある。

次の例では、設定が存在しない場合の処理を追加している:

C#
using System;
using System.Configuration;

class Program
{
    static void Main()
    {
        try
        {
            string apiEndpoint = ConfigurationManager.AppSettings["ApiEndpoint"];
            if (string.IsNullOrEmpty(apiEndpoint))
            {
                throw new Exception("ApiEndpointの設定が見つかりません。");
            }
            Console.WriteLine($"APIエンドポイント: {apiEndpoint}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"エラー: {ex.Message}");
        }
    }
}

このように例外処理を加えることで、想定外のエラーを防ぐことができる。

設定ファイルへの書き込み

次に、設定ファイルへ書き込む方法を示す。これは通常、カスタマイズ可能な値をアプリケーションの終了時に保存する場合に利用される。

C#
using System;
using System.Configuration;
using System.Xml;

class Program
{
    static void Main()
    {
        // 新しい値を書き込む例
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.Settings["ApiEndpoint"].Value = "https://newapi.example.com";
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

        Console.WriteLine("設定が更新されました。");
    }
}

これで、設定値を動的に変更できる。

ウィンドウのサイズと位置の管理

以下は、ウィンドウのサイズを設定ファイルから読み込み、アプリ終了時に保存する例だ。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="WindowWidth" value="800" />
    <add key="WindowHeight" value="600" />
  </appSettings>
</configuration>
C#
using System;
using System.Configuration;
using System.Windows.Forms;

namespace Practice
{
    public class MainForm : Form
    {
        public MainForm()
        {
            this.Load += new EventHandler(MainForm_Load);
            this.FormClosing += new FormClosingEventHandler(MainForm_FormClosing);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // ウィンドウサイズを読み込み
            int width = int.Parse(ConfigurationManager.AppSettings["WindowWidth"] ?? "800");
            int height = int.Parse(ConfigurationManager.AppSettings["WindowHeight"] ?? "600");

            this.Width = width;
            this.Height = height;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // ウィンドウサイズを保存
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["WindowWidth"].Value = this.Width.ToString();
            config.AppSettings.Settings["WindowHeight"].Value = this.Height.ToString();
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

    }
}

この方法で、ユーザー設定を柔軟に管理できる。

その他のメソッド

Configurationクラスには、設定の追加や削除などの機能もある。以下は、キーを追加する例だ:

C#
using System;
using System.Configuration;

class Program
{
    static void Main()
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        config.AppSettings.Settings.Add("NewSetting", "NewValue");
        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("appSettings");

        Console.WriteLine("新しい設定が追加されました。");
    }
}

これでアプリケーションの柔軟性がさらに向上する。

このブログを検索

QooQ