「アプリケーション構成ファイル」を使用して設定を読み込む「アプリケーション構成ファイル」とは、アプリケーション固有の設定が記述されたXML形式のファイルです。詳しくは、「アプリケーション構成ファイル」等をご覧ください。 ここでは、「アプリケーション構成ファイル」への設定の記述と、その設定を読み込む簡単な方法を示します。 1.Visual Studioでは、ソリューションエクスプローラでプロジェクトを右クリックしてポップアップメニューを表示させ、「追加」-「新しい項目の追加」で「アプリケーション構成ファイル」を選び、「アプリケーション構成ファイル」を作成します。このアプリケーション構成ファイルは、ファイル名「App.config」(Webアプリケーションでは web.config)としてプロジェクトに追加され、EXEファイルと同じフォルダに「(EXEファイル名).config」という名前でコピーされます(例えば、"Project1.exe"という名前のアプリケーションでは、"Project1.exe.config"という名前になります)。はじめのアプリケーション構成ファイルの中身は次のようになっています。 <?xml version="1.0" encoding="utf-8" ?> <configuration> </configuration> 2.次のように<appSettings>要素を追加し、さらにその中に<add>要素を必要なだけ追加していきます。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
<add key="Application Version" value="1.0.0.0" />
<add key="Comment" value="Hoge Hoge" />
</appSettings>
</configuration>
3.「アプリケーション構成ファイル」から設定を読み込むためには、次のようなコードを書きます。 .NET Framework 1.1以前の場合 [VB.NET] '指定したキーの値を取得 Console.WriteLine(System.Configuration.ConfigurationSettings.AppSettings("Comment")) 'すべてのキーとその値を取得 Dim key As String For Each key In System.Configuration.ConfigurationSettings.AppSettings.AllKeys Console.WriteLine("{0} : {1}", _ key, System.Configuration.ConfigurationSettings.AppSettings(key)) Next [C#] //指定したキーの値を取得 Console.WriteLine(System.Configuration.ConfigurationSettings.AppSettings["Comment"]); //すべてのキーとその値を取得 foreach (string key in System.Configuration.ConfigurationSettings.AppSettings.AllKeys) { Console.WriteLine("{0} : {1}", key, System.Configuration.ConfigurationSettings.AppSettings[key]); } .NET Framework 2.0以降の場合(参照にSystem.Configuration.dllを加える必要あり) [VB.NET] '指定したキーの値を取得 '見つからないときはNothingを返す Console.WriteLine(System.Configuration.ConfigurationManager.AppSettings("Comment")) 'すべてのキーとその値を取得 Dim key As String For Each key In System.Configuration.ConfigurationManager.AppSettings.AllKeys Console.WriteLine("{0} : {1}", _ key, System.Configuration.ConfigurationManager.AppSettings(key)) Next key [C#] //指定したキーの値を取得 //見つからないときはnullを返す Console.WriteLine(System.Configuration.ConfigurationManager.AppSettings["Comment"]); //すべてのキーとその値を取得 foreach (string key in System.Configuration.ConfigurationManager.AppSettings.AllKeys) { Console.WriteLine("{0} : {1}", key, System.Configuration.ConfigurationManager.AppSettings[key]); } 上記の結果、次のように出力されます。 Hoge Hoge Application Name : MyApplication Application Version : 1.0.0.0 Comment : Hoge Hoge Visual Studioを使わなくても、上記のようなアプリケーション構成ファイルを自分で作成すればOKです。
注意:この記事では、基本的な事柄の説明が省略されているかもしれません。初心者の方は、特に以下の点にご注意ください。
|
|
Copyright 2002-2008 DOBON!. All rights reserved.
|