C Sharp/DLLのApp.config

提供: MonoBook
< C Sharp
2012年8月3日 (金) 13:50時点における61.125.42.8 (トーク)による版
ナビゲーションに移動 検索に移動

.NET FrameworkDLLライブラリ)でApp.configアプリケーション構成ファイル)を使う方法を記述する。

手順

もっといい方法があると思うが、知っている人がいたら教えて欲しい。

ライブラリプロジェクト内にApp.configファイルを作る

  1. ライブラリプロジェクトにApp.configアプリケーション構成ファイル)を追加する。
  2. ファイル名を「DLL名」+「.config」に変更する。
    たとえば「monobooklib.dll」であれば「monobooklib.dll.config」とする。
  3. Visual Studioでファイルのプロパティを開き、「出力ディレクトリにコピー」の値を「常にコピーする」に設定する。


なお、app.configの中身の書き方は同じ。

.dll.configファイルを読み込むクラスを作る

C#での記述例。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Configuration;

    public static class ConfigUtil
    {
        public static System.Configuration.Configuration GetConfig(Type type)
        {
            string dll_config_path = type.Assembly.Location + ".config";
            
            if (!File.Exists(dll_config_path))
            {
                return null;
            }

            var file_map = new ExeConfigurationFileMap();
            file_map.ExeConfigFilename = dll_config_path;
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file_map, ConfigurationUserLevel.None);

            return config;
        }
    }

使ってみる

以下の設定ファイルはライブラリプロジェクトにあるものとする。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="hello"  value="monobook" />
  </appSettings>
</configuration>

以下のコードはライブラリプロジェクトにあるものとする。

    public class TestClass
    {
        public string Name { get; set; }

        public TestClass()
        {
            var config = ConfigUtil.GetConfig(this.GetType());
            var setting = config.AppSettings.Settings["hello"];
            if (setting != null)
            {
                this.Name = setting.Value;
            }
        }
    }

以下のコードはライブラリプロジェクトとは別にあるものとする。

    using System;
    
    class Program
    {
        static void Main(string[] args)
        {
            var test = new TestClass();
            Console.WriteLine(test.Name);
        }
    }

関連項目

参考文献

外部リンク