差分

ナビゲーションに移動 検索に移動

C Sharp/DLLのApp.config

2,825 バイト追加, 2012年8月3日 (金) 13:49
ページの作成:「.NET FrameworkDLLライブラリ)でApp.configアプリケーション構成ファイル)を使う方法を記述する。 == ライ...」
[[.NET Framework]]の[[DLL]]([[ライブラリ]])で[[App.config]]([[アプリケーション構成ファイル]])を使う方法を記述する。

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


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

== .dll.configファイルを読み込むクラスを作る ==
[[C Sharp|C#]]での記述例。
<source lang="csharp">
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;
}
}
</source>

== 使ってみる ==
以下の設定ファイルはライブラリプロジェクトにあるものとする。
<source lang="xml">
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="hello" value="monobook" />
</appSettings>
</configuration>
</source>

以下のコードはライブラリプロジェクトにあるものとする。
<source lang="csharp">
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;
}
}
}
</source>

以下のコードはライブラリプロジェクトとは別にあるものとする。
<source lang="csharp">
using System;

class Program
{
static void Main(string[] args)
{
var test = new TestClass();
Console.WriteLine(test.Name);
}
}
</source>

== 関連項目 ==
* [[.NET Framework]]
* [[C Sharp|C#]]

== 参考文献 ==
{{reflist}}

== 外部リンク ==

{{stub}}
匿名利用者

案内メニュー