【C#】外部ファイル(App.config)の読み書き
環境
- .NET Framework 4.6
- VisualStudio2017 Community
手順
1.System.Configurationの参照設定を追加
ソリューションエクスプローラーの参照を右クリック→【参照の追加】を選択 System.Configurationを検索し、見つかったら、チェックを入れてOKを選択します。
2.App.configに設定値を追加
AppConfigを開き、次のように<appSettings>の要素に設定値を追加してください。
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <!--追加--> <appSettings> <add key="key1" value="value1" /> <add key="key2" value="value2" /> </appSettings> </configuration>
3.設定値の読み込み
次のの参照を冒頭に追加する。 using System.Configuration;
次のようにConfigurationManager.AppSettings["キー名"]で呼び出す
using System.Configuration;//追加 namespace SamplePrj { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //読み込み処理 MessageBox.Show(ConfigurationManager.AppSettings["key1"]); } } }
こんな感じ
4.設定値の保存
using System.Configuration; namespace SamplePrj { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //書き込み処理 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["key2"].Value = "こんにちわ"; config.Save(); } } }
以上です。