C#/설정파일2013. 9. 6. 08:02

몇달전에 소소한 배치프로그램을 만들어야 되는 경우가 생겼다.

몇가지 설정에 따른것들도 손을 봐야 해서 그때 조잡하지만 하나 만들어 둔것이 생각나서 이렇게 포스팅한다.

예를 들어서

이런형태로 프로그램에서 사용해야 되는 기초적인 변수값등을 넣어두고 그것을 프로그램에서 이용해야 되는경우이다.

여기서 우리는 SOURCE 의 값과, Editor의 값을 프로그램이 실행시에 가져와야 된다는것이다.

이것을 Key와 Value값으로 가져오는 방식의 코딩을 할때 C# 은 여타 언어에 비해서 탁월하게 편리함을 자랑한다.

 

public class SettingTextFile

    {

        public static string FullPath;

        public static Dictionary<string, string> Setting;

        public static void ReadSettingTextFile(string fullPath)

        {

            Setting = new Dictionary<string, string>();

            FullPath = fullPath;

            ReadSettingFile();

        }

 

        static void ReadSettingFile()

        {

            string[] strs = File.ReadAllLines(FullPath, Encoding.GetEncoding("ks_c_5601-1987"));

            foreach (string str in strs)

            {

                string tmp = str.TrimStart();

                if (tmp.StartsWith("#")) continue; //주석의 경우 넘김

                int position = tmp.IndexOf('=');

                if (position < 1) continue;

               

                string Key = tmp.Substring(0, position).Trim();

                if (Key.Length == 0) continue;

 

                string Value = tmp.Substring(position + 1, tmp.Length - (position + 1)).Trim();

                Setting[Key.ToUpper()] = Value;

            }

        }

 

        public static void ReadAgain()

        {

            Setting.Clear();

            ReadSettingFile();

        }

 

        public static string GetValue(string key)

        {

            if (Setting.ContainsKey(key))

                return Setting[key];

            else

                return string.Empty;

        }

    }

 

결과

 

사용법은

SettingTextFile.ReadSettingTextFile(@"C:\SettingTextFile.txt");

의 구문을 프로그램 시작할때 넣어주고

사용하고자 하는곳에서는

SettingTextFile.Setting[“키값”] 을 가지고 사용하면 된다.

 

 

Posted by 설계와구현