
INI 파일을 로드하고 초기화하는 방법에 대해 설명하겠습니다.
INI 파일은 Windows 운영체제에서 사용하는 파일 형식으로, 설정 값을 저장하는 데 사용됩니다. C#에서 INI 파일을 로드하고 초기화하는 방법은 `IniFileReader` 클래스를 사용하는 것입니다.
`IniFileReader` 클래스는 INI 파일을 읽어와 설정 값을 가져올 수 있습니다. 이 클래스는 `IniFileReader` 클래스의 `IniFileReader` 인스턴스를 생성하여 INI 파일을 로드하는 방법을 제공합니다.
`IniFileReader` 클래스의 `IniFileReader` 인스턴스를 생성할 때, INI 파일의 경로를 지정해야 합니다. 이 경로는 INI 파일의 위치를 나타내며, 파일이 존재하지 않으면 예외가 발생합니다.
INI 파일을 로드한 후, `IniFileReader` 클래스의 `GetSection` 메서드를 사용하여 특정 섹션의 설정 값을 가져올 수 있습니다. 이 메서드는 섹션 이름을 인수로 받아 섹션의 설정 값을 반환합니다.
INI 파일을 로드하고 초기화하는 예제를 살펴보겠습니다.
#hostingforum.kr
csharp
using System;
using System.IO;
using System.Configuration;
class IniFileReader
{
private string _filePath;
public IniFileReader(string filePath)
{
_filePath = filePath;
}
public string GetSection(string sectionName)
{
try
{
using (StreamReader reader = new StreamReader(_filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith(sectionName + "."))
{
string[] keyValue = line.Split('=');
return keyValue[1].Trim();
}
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("INI 파일이 존재하지 않습니다.");
}
return null;
}
}
class Program
{
static void Main()
{
string filePath = "example.ini";
IniFileReader reader = new IniFileReader(filePath);
string sectionName = "Settings";
string value = reader.GetSection(sectionName);
if (value != null)
{
Console.WriteLine($"섹션 {sectionName}의 설정 값은 {value}입니다.");
}
else
{
Console.WriteLine($"섹션 {sectionName}이 존재하지 않습니다.");
}
}
}
위 예제에서는 `IniFileReader` 클래스를 사용하여 INI 파일을 로드하고 특정 섹션의 설정 값을 가져옵니다. `GetSection` 메서드는 섹션 이름을 인수로 받아 섹션의 설정 값을 반환합니다.
INI 파일을 로드하고 초기화하는 방법은 위 예제와 유사합니다. INI 파일을 로드한 후, `IniFileReader` 클래스의 `GetSection` 메서드를 사용하여 특정 섹션의 설정 값을 가져올 수 있습니다.
2025-03-04 22:54