.NET FrameworkのDLL(ライブラリ)でApp.config(アプリケーション構成ファイル)を使う方法を記述する。
目次
手順
もっといい方法があると思うが、知っている人がいたら教えて欲しい。
ライブラリプロジェクト内にApp.configファイルを作る
- ライブラリプロジェクトにApp.config(アプリケーション構成ファイル)を追加する。
- ファイル名を「DLL名」+「.config」に変更する。
- たとえば「monobooklib.dll」であれば「monobooklib.dll.config」とする。
- 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);
}
}