4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#でconfigファイルを使うやり方メモ

Posted at

C#で作ったデスクトップアプリケーションにおいて、
アプリを閉じた時に設定データが保存され、次に開いた時に反映されるしくみを作りたい。

.configファイルを使用し、アプリ終了時に書き込み、アプリ起動時に読み出し、とすることで対応できた。
自分用のメモとして残しておく。

config.cs
using System.Configuration;

namespace ConfigMake
{
    class DataMod
    {
        public string FileName { get; set; }
        public string StartTime { get; set; }
        public string EndTime { get; set; }
        public string Class { get; set; }
        public string Code { get; set; }
        public string Reason { get; set; }
        public string Approver { get; set; }

         public void LogLoad()
        {
            var configFile = @"test.config";
            var exeFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
            var config = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None);

            // config読みだし
            FileName = config.AppSettings.Settings["FileName"].Value;
            StartTime = config.AppSettings.Settings["StartTime"].Value;
            EndTime = config.AppSettings.Settings["EndTime"].Value;
            Class = config.AppSettings.Settings["Class"].Value;
            Code = config.AppSettings.Settings["Code"].Value;
            Reason = config.AppSettings.Settings["Reason"].Value;
            Approver = config.AppSettings.Settings["Approver"].Value;


        }

        public void LogSave()
        {
            var configFile = @"test.config";
            var exeFileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
            var config = ConfigurationManager.OpenMappedExeConfiguration(exeFileMap, ConfigurationUserLevel.None);

            // config書き込み
            config.AppSettings.Settings["FileName"].Value = FileName;
            config.AppSettings.Settings["StartTime"].Value = StartTime;
            config.AppSettings.Settings["EndTime"].Value = EndTime;
            config.AppSettings.Settings["Class"].Value = Class;
            config.AppSettings.Settings["Code"].Value = Code;
            config.AppSettings.Settings["Reason"].Value = Reason;
            config.AppSettings.Settings["Approver"].Value = Approver;

            config.Save();

        }
    }
   
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?