開發接口程序時,對於接口程序配置的IP地址、端口等都需要是可配置的,而在Win Api原生實現了INI文件的讀寫操作,因此只需要調用Win Api中的方法即可操作INI配置文件,關鍵代碼就是如何調用Win Api中的方法,如下所示:
#region 調用WinApi 原方法聲明 [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); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath); #endregion
具體代碼如下所示(刪除段落內容是參考蘇飛論壇蘇飛大神的):
using System; using System.Text; using System.Runtime.InteropServices; namespace DotNetCommon.File { /// <summary> /// 類說明:INI文件讀寫類 /// 編碼人:鞠小軍 /// 聯系方式:[email protected] /// </summary> public class IniFileHelper { /// <summary> /// INI文件路徑 /// </summary> public string Path; /// <summary> /// 屏蔽空的構造函數 /// </summary> public IniFileHelper() { throw new Exception("不允許使用空的構造函數!"); } /// <summary> /// 構造函數,參數為INI文件路徑 /// </summary> /// <param name="path">INI文件的路徑</param> public IniFileHelper(string path) { Path = path; } #region 調用WinApi 原方法聲明 [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); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath); #endregion /// <summary> /// 讀取INI文件 /// </summary> /// <param name="section">段落</param> /// <param name="key">鍵</param> /// <returns></returns> public string IniReadValue(string section, string key) { var temp = new StringBuilder(255); var i = GetPrivateProfileString(section, key, "", temp, 255, Path); return temp.ToString(); } /// <summary> /// 寫入INI文件 /// </summary> /// <param name="section">段落</param> /// <param name="key">鍵</param> /// <param name="value">值</param> public void IniWriteValue(string section, string key, string value) { WritePrivateProfileString(section, key, value, Path); } /// <summary> /// 清楚INI文件中所有的段落 /// </summary> public void ClearAllSection() { IniWriteValue(null, null, null); } /// <summary> /// 清楚INI文件中指定段落內容 /// </summary> /// <param name="section">段落</param> public void ClearSection(string section) { IniWriteValue(section, null, null); } } } View Codestring path = Application.StartupPath + "\\config.ini";
IniWriteValue(path,"config","password",textBox1.Text.Trim());
ini文件從來就不放代碼。是配置文件,沒有可執行的東西。
要實現執行其他的文件的代碼,那麼你寫的本來就是一個解析器。