在一些C/S程序中我们经常会使用INI配置文件
优点:1.灵活。
2.相对于一些数据量的程序,相对使用数据库更节约资源。
/// <summary> /// 配置文件操作类 /// </summary> internal static class OperConfigFile { private static string _filePath = string.Format("{0}\{1}", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "kaiteConfig.ini"); [DllImport("kernel32", CharSet = CharSet.Unicode)] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); //xiexie [DllImport("kernel32", CharSet = CharSet.Unicode)] private static extern int WritePrivateProfileString(string section, string key, string val, string filePath); /// <summary> /// 对ini文件进行读操作的函数 /// </summary> /// <param name="Section">选择项</param> /// <param name="Key">关键值</param> /// <param name="TextLength">需要返回文本的最大长度</param> /// <returns>返回文本值</returns> public static string IniReadValue(string Section, string Key, int TextLength) { StringBuilder temp = new StringBuilder(TextLength); int i = GetPrivateProfileString(Section, Key, "", temp, TextLength, _filePath); return temp.ToString(); } /// <summary> /// 对ini文件进行写操作的函数 /// </summary> /// <param name="Section">选项</param> /// <param name="Key">关键字</param> /// <param name="Value">值</param> public static void IniWriteValue(string Section, string Key, StringBuilder Value) { WritePrivateProfileString(Section, Key, Value.ToString(), _filePath); } /// <summary> /// 对ini文件进行读操作的函数 /// </summary> /// <param name="Section">选择项</param> /// <param name="Key">关键值</param> /// <param name="TextLength">需要返回文本的最大长度</param> /// <returns>返回文本值</returns> private static string IniReadValue(string Section, string Key, int TextLength, string path) { StringBuilder temp = new StringBuilder(TextLength); int i = GetPrivateProfileString(Section, Key, "", temp, TextLength, path); return temp.ToString(); } /// <summary> /// 写日志 /// </summary> /// <param name="fileName">文件名</param> /// <param name="context">内容</param> public static void WriteLog(string fileName, string context) { try { if (IniReadValue("LogConfig", "log", 10, string.Format("{0}\{1}", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "CQFJ_CONFIG.ini")) == "1") { string filePathTemp = string.Format("{0}\日志\SysLog_{1}_{2}.txt", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), DateTime.Now.ToString("yyyy-MM-dd"), fileName); WritePrivateProfileString(DateTime.Now.Date.ToString(), DateTime.Now.TimeOfDay.ToString(), context, filePathTemp); } } catch { } } }