1. 소스
/// <summary>
/// INI파일의 파서
/// </summary>
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class IniParser : IIniParser
{
private Hashtable KeyPairs = new Hashtable();
private string IniFilePath = "";
/// <summary>
/// 대소문자 구분을 하는지의 여부
/// </summary>
private bool ToCase = false;
/// <summary>
/// INI파일을 오픈했는지의 여부
/// </summary>
public bool IsOpened = false;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private class StringPair
{
/// <summary>
/// 순번 (키)
/// </summary>
public int Index;
/// <summary>
/// 값
/// </summary>
public string Value;
/// <summary>
/// 설명
/// </summary>
public string Memo;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct SectionPair
{
/// <summary>
/// 순번 (키)
/// </summary>
public int Index;
/// <summary>
/// 세션
/// </summary>
public StringPair Section;
/// <summary>
/// 세션의 키
/// </summary>
public StringPair Key;
}
/// <summary>
/// Opens the INI file at the given path and enumerates the values in the IniParser.
/// </summary>
/// <param name="iniPath">Full path to INI file.</param>
/// <param name="to_upper">모든 내용을 대문자로 인식할지의 여뷰</param>
public IniParser(string iniPath, bool to_upper = false)
{
try
{
IsOpened = Open(iniPath, to_upper);
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
}
/// <summary>
/// Opens the INI file at the given path and enumerates the values in the IniParser.
/// </summary>
/// <param name="iniPath">Full path to INI file.</param>
/// <param name="to_upper">모든 내용을 대문자로 인식할지의 여뷰</param>
public bool Open(string iniPath, bool to_upper = false)
{
TextReader iniFile = null;
string strLine = null;
StringPair currentRoot = null;
string[] keyPair = null;
string memo = "";
IniFilePath = iniPath;
ToCase = to_upper;
if (File.Exists(iniPath))
{
try
{
iniFile = new StreamReader(iniPath, Encoding.Default);
strLine = iniFile.ReadLine();
int sessionIndex = 0;
int keyIndex = 0;
while (strLine != null)
{
if (to_upper)
strLine = strLine.Trim().ToUpper();
else
strLine = strLine.Trim();
if (!string.IsNullOrWhiteSpace(strLine))
{
if (strLine[0] == ';')
{// 주석 처리
memo += strLine + "\r\n";
strLine = iniFile.ReadLine();
continue;
}
else if (strLine.StartsWith("[") && strLine.EndsWith("]"))
{
currentRoot = new StringPair()
{
Index = ++sessionIndex,
Value = strLine.Substring(1, strLine.Length - 2),
Memo = memo,
};
keyIndex = 0;
memo = "";
}
else
{
keyPair = strLine.Split(new char[] { '=' }, 2);
SectionPair sectionPair = new SectionPair();
string value = null;
if (currentRoot == null)
{
currentRoot = new StringPair()
{
Index = ++sessionIndex,
Value = "ROOT",
Memo = memo,
};
keyIndex = 0;
memo = "";
}
sectionPair.Section = currentRoot;
sectionPair.Key = new StringPair()
{
Index = ++keyIndex,
Value = keyPair[0],
Memo = memo,
};
if (keyPair.Length > 1)
value = keyPair[1];
KeyPairs.Add(sectionPair, value);
}
}
memo = "";
strLine = iniFile.ReadLine();
}
return true;
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
finally
{
if (iniFile != null)
iniFile.Close();
}
}
else
KLog.Write("Unable to locate " + iniPath);
return false;
}
/// <summary>
/// INI파일을 오픈했는지의 여부
/// </summary>
/// <returns>INI파일을 오픈했는지의 여부</returns>
public bool IsNull()
{
return IsOpened == false;
}
/// <summary>
/// Returns the value for the given section, key pair.
/// </summary>
/// <param name="sectionName">Section name.</param>
/// <param name="settingName">Key name.</param>
public string GetSetting(string sectionName, string settingName)
{
SectionPair sectionPair = new SectionPair();
try
{
var session = (from SectionPair v in KeyPairs.Keys
where (ToCase && v.Section.Value.ToUpper() == sectionName) ||
(!ToCase && v.Section.Value == sectionName)
select v.Section).FirstOrDefault();
if (session == null)
{
KLog.WriteFormat("세션 [{0}]이 없습니다.", sectionName);
return "";
}
var key = (from SectionPair v in KeyPairs.Keys
where ((ToCase && v.Section.Value.ToUpper() == sectionName) ||
(!ToCase && v.Section.Value == sectionName)) &&
((ToCase && v.Key.Value.ToUpper() == settingName) ||
(!ToCase && v.Key.Value == settingName))
select v.Key).FirstOrDefault();
if (key == null)
{
KLog.WriteFormat("세션 [{0}]의 키 [{1}]가 없습니다.", sectionName, settingName);
return "";
}
sectionPair.Section = session;
sectionPair.Key = key;
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
return KeyPairs[sectionPair].ToString();
}
/// <summary>
/// Enumerates all lines for given section.
/// </summary>
/// <param name="sectionName">Section to enum.</param>
/// <returns>입력된 순서대로 세션의 리스트를 반환</returns>
public string[] EnumSection(string sectionName)
{
ArrayList tmpArray = new ArrayList();
try
{
var sessions = (from SectionPair v in KeyPairs.Keys
where ToCase ? v.Section.Value.ToUpper() == sectionName.ToUpper() : v.Section.Value == sectionName
select v);
if (sessions.Count() > 0)
{
var list = (from SectionPair v in sessions
orderby v.Key.Index
select v.Key.Value + "=" + KeyPairs[v])
.ToArray();
return list;
}
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
return (string[])tmpArray.ToArray(typeof(string));
}
/// <summary>
/// Adds or replaces a setting to the table to be saved.
/// </summary>
/// <param name="sectionName">Section to add under.</param>
/// <param name="settingName">Key name to add.</param>
/// <param name="settingValue">Value of key.</param>
public void AddSetting(string sectionName, string settingName, string settingValue)
{
SectionPair sectionPair = new SectionPair();
try
{
bool isNewSession = false;
var session = (from SectionPair v in KeyPairs.Keys
where (ToCase && v.Section.Value.ToUpper() == sectionName) ||
(!ToCase && v.Section.Value == sectionName)
select v.Section).FirstOrDefault();
if (session == null)
{
KLog.WriteFormat("세션 [{0}]를 생성합니다.", sectionName);
var last = (from SectionPair v in KeyPairs.Keys
orderby v.Section.Index descending
select v.Section.Index).FirstOrDefault();
session = new StringPair()
{
Index = last + 1,
Value = sectionName,
};
isNewSession = true;
}
var key = (from SectionPair v in KeyPairs.Keys
where (ToCase && v.Key.Value.ToUpper() == settingName) ||
(!ToCase && v.Key.Value == settingName)
select v.Key).FirstOrDefault();
if (key == null)
{
KLog.WriteFormat("세션 [{0}]의 키 [{1}]를 생성합니다.", sectionName, settingName);
int last;
if (isNewSession)
last = 0;
else
last = (from SectionPair v in KeyPairs.Keys
where (ToCase && v.Section.Value.ToUpper() == sectionName) ||
(!ToCase && v.Section.Value == sectionName)
orderby v.Key.Index descending
select v.Key.Index).FirstOrDefault();
key = new StringPair()
{
Index = last + 1,
Value = settingName,
};
}
sectionPair.Section = session;
sectionPair.Key = key;
if (KeyPairs.ContainsKey(sectionPair))
KeyPairs[sectionPair] = settingValue;
else
KeyPairs.Add(sectionPair, settingValue);
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
}
/// <summary>
/// Adds or replaces a setting to the table to be saved with a null value.
/// </summary>
/// <param name="sectionName">Section to add under.</param>
/// <param name="settingName">Key name to add.</param>
public void AddSetting(string sectionName, string settingName)
{
AddSetting(sectionName, settingName, null);
}
/// <summary>
/// Remove a setting.
/// </summary>
/// <param name="sectionName">Section to add under.</param>
/// <param name="settingName">Key name to add.</param>
public void DeleteSetting(string sectionName, string settingName)
{
SectionPair sectionPair = new SectionPair();
try
{
var session = (from SectionPair v in KeyPairs.Keys
where (ToCase && v.Section.Value.ToUpper() == sectionName) ||
(!ToCase && v.Section.Value == sectionName)
select v.Section).FirstOrDefault();
if (session == null)
{
KLog.WriteFormat("세션 [{0}]이 없습니다.", sectionName);
return;
}
var key = (from SectionPair v in KeyPairs.Keys
where (ToCase && v.Key.Value.ToUpper() == settingName) ||
(!ToCase && v.Key.Value == settingName)
select v.Key).FirstOrDefault();
if (key == null)
{
KLog.WriteFormat("세션 [{0}]의 키 [{1}]가 없습니다.", sectionName, settingName);
return;
}
sectionPair.Section = session;
sectionPair.Key = key;
if (KeyPairs.ContainsKey(sectionPair))
KeyPairs.Remove(sectionPair);
}
catch (Exception ex)
{
KLog.Write(ex.ToString());
}
}
/// <summary>
/// Save settings to new file.
/// </summary>
/// <param name="newFilePath">New file path.</param>
public void SaveSettings(string newFilePath)
{
ArrayList sections = new ArrayList();
string tmpValue = "";
string strToSave = "";
var list = (from SectionPair v in KeyPairs.Keys
orderby v.Section.Index, v.Key.Index
select v.Section).Distinct();
foreach (StringPair v in list)
{
if (v.Memo != string.Empty)
strToSave += v.Memo;
strToSave += "[" + v.Value + "]\r\n";
var keylist = from SectionPair vv in KeyPairs.Keys
where (ToCase && vv.Section.Value.ToUpper() == v.Value) ||
(!ToCase && vv.Section.Value == v.Value)
orderby vv.Key.Index
select vv;
foreach (SectionPair vv in keylist)
{
if (vv.Key.Memo != string.Empty)
strToSave += vv.Key.Memo;
tmpValue = (string)KeyPairs[vv];
if (tmpValue != string.Empty)
strToSave += (vv.Key.Value + "=" + tmpValue + "\r\n");
else
strToSave += (vv.Key.Value + "=\r\n");
}
strToSave += "\r\n";
}
#if (OLD_VERSION)
foreach (SectionPair sectionPair in KeyPairs.Keys)
{
if (!sections.Contains(sectionPair.Section))
sections.Add(sectionPair.Section);
}
foreach (StringPair section in sections)
{
strToSave += ("[" + section.Value + "]\r\n");
foreach (SectionPair sectionPair in KeyPairs.Keys)
{
if (sectionPair.Section.Value == section.Value)
{
tmpValue = (StringPair)KeyPairs[sectionPair];
if (tmpValue != null)
tmpValue.Value = "=" + tmpValue.Value;
strToSave += (sectionPair.Key.Value + tmpValue.Value + "\r\n");
}
}
strToSave += "\r\n";
}
#endif
try
{
using (StreamWriter sw = new StreamWriter(newFilePath, false, Encoding.Default))
{
sw.Write(strToSave);
sw.Close();
}
//Stream fs = new FileStream(newFilePath, FileMode.Create, FileAccess.Write);
//TextWriter tw = new StreamWriter(fs, Encoding.Default);
//tw.Write(strToSave);
//tw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Save settings back to ini file.
/// </summary>
/// <param name="method">정렬방법</param>
public void SaveSettings()
{
SaveSettings(IniFilePath);
}
}
}
2. 사용예제
INI.IniParser iniParser = new INI.IniParser(inipath);
string MainIP = iniParser.GetSetting("SETTING", "MainIP");
3. ini 파일의 내용
[SETTING]
;DB 서버 IP
DataSource=192.168.0.18
;DB 명칭
DBname=AE_SAIDataDB
;DB 사용자 ID
UserId=sa
;DB 사용자 암호
Password=ubasic0901!
;DB 접속 대기시간
ConnectTimeout=120
;어시스트모니터가 표시될 화면번호 (0=기본모니터)
MONITOR=1
;메인모니터가 실행되고 있는 컴퓨터의 IP
MainIP=127.0.0.1
'유용한 정보' 카테고리의 다른 글
[C#] DataGridView 컨트롤에서 열 고정하기 (0) | 2025.04.16 |
---|---|
[C#] 문자열을 속성으로 갖는 클래스 만들기 (0) | 2025.04.16 |
[C#] 컨트롤에 들어갈 문자열의 폭과 높이 구하기 (0) | 2025.04.16 |
[C#] 컨트롤에 들어갈 문자열에서 가장 큰 폭과 높이 구하기 (0) | 2025.04.16 |
[C#] DataGridView 에 수직스크롤바가 있는지의 여부 판단하기 (0) | 2025.04.16 |