.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 전체가 사라집니다.
*/
}
}
}

'C# > Windows Form' 카테고리의 다른 글
[C# Windows Form] FormBorderStyle = None 인 경우 모니터 위치에 맞게 최대화 시키기 (0) | 2022.07.26 |
---|---|
[C# Windows Form] ListView 기본 사용법 (1) 컬럼 및 아이템 (0) | 2022.06.15 |
[C# Windows Form] 이미지 회전 시키기 (Image, Graphics) (0) | 2022.05.05 |
[C# Windows Form] 마우스 매크로 만들기 (0) | 2022.04.28 |
[C# Windows Form] 화면 캡쳐하기 (Bitmap .png) (0) | 2022.03.05 |