.ini 파일은 메모장으로도 열리고 initialization 을 의미 합니다.

초기화 할 때 사용할 영역(section), 키(key), 값(value)을 가지고 있습니다.

저처럼 쫄지마세요.. 되게 간단합니다!

 

Write할 때 딱 세 가지만 아시면 됩니다.

1. 섹션이 없다면 섹션이 생성되고 키도 없다면 생성 됩니다. (키, 값이 해당 섹션으로 추가 됩니다.)

2. 동일한 키가 있다면 덮어 씌여집니다.

3. 삭제는 null 값으로 써주면 됩니다. (키 삭제, 섹션 삭제 가능)

 

예제 코드와 결과입니다.


using System;
using System.IO;
using System.Text;
using System.Runtime.InteropServices; //DllImport

namespace ConsoleApp2
{
    class Program
    {
        [DllImport("kernel32.dll")]
        private static extern uint GetPrivateProfileString(string section,
                                                           string key,
                                                           string defaultValue, //키값이 없을 때의 기본 값
                                                           StringBuilder returnedString,
                                                           int size,
                                                           string filePath);

        //************************************************************
        //section 혹은 key 가져오기 위한 바이트배열
        [DllImport("kernel32.dll")]
        private static extern uint GetPrivateProfileString(string section,
                                                           string key,
                                                           string defaultValue, //키값이 없을 때의 기본 값
                                                           byte[] returnedString,
                                                           int size,
                                                           string filePath);
        //************************************************************

        [DllImport("kernel32.dll")]
        private static extern bool WritePrivateProfileString(string section,
                                                             string key,
                                                             string value,
                                                             string filePath);

        static void Main(string[] args)
        {
            string filePath = Path.Combine(Environment.CurrentDirectory, "test.ini");

            //파일이 없다면 만들어줍니다. 해당 프로젝트 Debug 폴더에 위치합니다.
            if (File.Exists(filePath) == false)
            {
                File.Create(filePath);
            }

            //*********************** 쓰기
            WritePrivateProfileString("Section1", "key1", "value1", filePath);
            WritePrivateProfileString("Section1", "key2", "value2", filePath);
            WritePrivateProfileString("Section1", "key333", "ooo", filePath);

            WritePrivateProfileString(null, null, null, filePath); //쓰기 직후 읽을 수 있도록 flush

            //*********************** 읽기
            StringBuilder sb = new StringBuilder { Capacity = 100 }; //프로퍼티 초기화 방식

            GetPrivateProfileString("Section1", "key1", "Nothing..", sb, sb.Capacity, filePath);
            Console.WriteLine(string.Format("[Section1]'s key1 = {0}", sb.ToString())); //Section1의 key1 값을 가져옵니다.

            GetPrivateProfileString("Section2", "key11", "Nothing..", sb, sb.Capacity, filePath);
            Console.WriteLine(string.Format("[Section1]'s key11 = {0}", sb.ToString())); //Section2가 없으므로 Nothing..이 나옵니다.

            //*********************** 조회 (섹션)
            byte[] sectionBytes = new byte[1024];
            GetPrivateProfileString(null, null, null, sectionBytes, sectionBytes.Length, filePath); //section들을 가져옵니다.

            string readData = Encoding.UTF8.GetString(sectionBytes);
            string[] sections = readData.Split(new string[] { "\0" }, StringSplitOptions.RemoveEmptyEntries); //null 제외한 배열 얻기.
            ShowArray(sections);
            Console.WriteLine();

            //*********************** 조회 (섹션1의 키 값)
            byte[] keyBytes = new byte[1024];
            GetPrivateProfileString("Section1", null, null, keyBytes, keyBytes.Length, filePath); //section들을 가져옵니다.

            string readData2 = Encoding.UTF8.GetString(keyBytes);
            string[] keys = readData2.Split(new string[] { "\0" }, StringSplitOptions.RemoveEmptyEntries); //null 제외한 배열 얻기.
            ShowArray(keys);
            Console.WriteLine();

            //*********************** 지우기
            WritePrivateProfileString("Section1", "key333", null, filePath); //key333을 지웁니다.

            /*
            WritePrivateProfileString("Section1", null, null, filePath); //Section1 전체가 사라집니다.
            */
        }

        static void ShowArray (string[] array)
        {
            int index = 0;
            foreach (string str in array)
            {
                Console.WriteLine("Array[{0}] : {1}", index++, str);
            }
        }
    }
}

 

key333은 지워졌음!

 

+ Recent posts