CSharpIni.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. class Program
  5. {
  6. static void Main()
  7. {
  8. string iniFilePath = "application.ini"; // 파일 경로를 적절히 수정하세요
  9. // INI 파일 읽기
  10. Dictionary<string, Dictionary<string, string>> iniData = ReadIniFile(iniFilePath);
  11. // INI 파일에서 값을 가져오기
  12. string server = iniData["Database"]["Server"];
  13. string username = iniData["Database"]["Username"];
  14. Console.WriteLine($"Server: {server}");
  15. Console.WriteLine($"Username: {username}");
  16. // INI 파일에 쓰기
  17. iniData["Application"]["LogLevel"] = "INFO"; // 값을 변경하거나 추가할 수 있습니다.
  18. WriteIniFile(iniFilePath, iniData);
  19. }
  20. static Dictionary<string, Dictionary<string, string>> ReadIniFile(string filePath)
  21. {
  22. var iniData = new Dictionary<string, Dictionary<string, string>>();
  23. string currentSection = null;
  24. foreach (string line in File.ReadLines(filePath))
  25. {
  26. if (line.StartsWith("[") && line.EndsWith("]"))
  27. {
  28. currentSection = line.Trim('[', ']');
  29. iniData[currentSection] = new Dictionary<string, string>();
  30. }
  31. else if (!string.IsNullOrWhiteSpace(currentSection))
  32. {
  33. string[] parts = line.Split('=');
  34. if (parts.Length == 2)
  35. {
  36. string key = parts[0].Trim();
  37. string value = parts[1].Trim();
  38. iniData[currentSection][key] = value;
  39. }
  40. }
  41. }
  42. return iniData;
  43. }
  44. static void WriteIniFile(string filePath, Dictionary<string, Dictionary<string, string>> iniData)
  45. {
  46. using (var writer = new StreamWriter(filePath))
  47. {
  48. foreach (var section in iniData)
  49. {
  50. writer.WriteLine($"[{section.Key}]");
  51. foreach (var kvp in section.Value)
  52. {
  53. writer.WriteLine($"{kvp.Key}={kvp.Value}");
  54. }
  55. }
  56. }
  57. }
  58. }