INI 檔案的詳細說明,可參考Windows 官方網站之說明(連結)
而Windows本身提供了 標準的 API 可以針對INI 檔進行操作與處理,分別為GetPrivateProfileString與WritePrivateProfileString。
然後上述兩個函數中的檔案名稱需要使用目標 INI 檔的完整路徑(需使用絕對路徑,不可使用相對路徑)。
然而程式可能都操作固定的某個 INI 檔,但是每次存取都需要取得該檔案之路徑,故將其行為進行簡易的彙整與處理。
並將其撰寫成 較方便使用的 Class 以便日後進行使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
using System; using System.IO; using System.Runtime.InteropServices; using System.Text; public class IniHelper : IDisposable { private const string INI_FILE_NAME = "init_setup.ini"; private static IniHelper _instance = null; public static IniHelper getInstance() { if (_instance == null) _instance = new IniHelper(INI_FILE_NAME); return _instance; } public enum IniSection { DefaultSetting,SystemSetting }; public enum IniKey { Web_URL,RULE_FILE_NAME } #region IniHeler Core [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool IsDisposing) { if (_bDisposed) return; _bDisposed = true; } private bool _bDisposed = false; private string _iniPath; ~IniHelper() { Dispose(false); } public IniHelper(string iniPath) { iniPath = Path.GetFullPath(Environment.CurrentDirectory + @"\" + iniPath); if (!File.Exists(iniPath)) { using (var fs = new FileStream(iniPath, FileMode.Create)) { new StreamWriter(fs, Encoding.UTF8); } } _iniPath = iniPath; } public void Set(IniSection section, IniKey key, string value) { Set(section.ToString(), key.ToString(), value); } public void Set(string section, string key, string value) { WritePrivateProfileString(section, key, value, _iniPath); } public T Get<T>(IniSection section, IniKey key, T defaultValue) { return Get(section.ToString(), key.ToString(), defaultValue); } public string Get(IniSection section, IniKey key) { return Get(section.ToString(), key.ToString()); } public T Get<T>(string section, string key, T defaultValue) { var result = Get(section, key); if (!string.IsNullOrEmpty(result)) { try { return (T)Convert.ChangeType(result, typeof(T)); } catch (Exception) { } } Set(section, key, defaultValue.ToString()); return defaultValue; } public string Get(string section, string key) { var temp = new StringBuilder(255); GetPrivateProfileString(section, key, string.Empty, temp, 255, _iniPath); return temp.ToString(); } #endregion } |
文章標籤
全站熱搜