.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,
                                                           uint 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);

            System.Threading.Thread.Sleep(1000); //Write 이 후 바로 못 읽기에 시간을 줍니다..

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

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

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

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

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

섹션도 더 추가할 수 있어요~!!

 

+ Recent posts