讀配置文件與寫配置文件的核心代碼如下:
1 [DllImport("kernel32")] 2 // 讀配置文件方法的6個參數:所在的分區(section)、鍵值、 初始缺省值、 StringBuilder、 參數長度上限、配置文件路徑 3 private static extern int GetPrivateProfileString(string section, string key, string deVal, StringBuilder retVal, 4 int size, string filePath); 5 6 [DllImport("kernel32")] 7 // 寫配置文件方法的4個參數:所在的分區(section)、 鍵值、 參數值、 配置文件路徑 8 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); 9 10 public static void SetValue(string section, string key, string value) 11 { 12 //獲得當前路徑,當前是在Debug路徑下 13 string strPath = Environment.CurrentDirectory + "\\system.ini"; 14 WritePrivateProfileString(section, key, value, strPath); 15 } 16 17 public static string GetValue(string section, string key) 18 { 19 StringBuilder sb = new StringBuilder(255); 20 string strPath = Environment.CurrentDirectory + "\\system.ini"; 21 //最好初始缺省值設置為非空,因為如果配置文件不存在,取不到值,程序也不會報錯 22 GetPrivateProfileString(section, key, "配置文件不存在,未取到參數", sb, 255, strPath); 23 return sb.ToString(); 24 25 } 26 27 28
【應用舉例】
功能說明:程序加載時,創建配置文件並往里面寫入波特率參數。(配置文件不需要事先存在,此Windows的API會自動創建)。點擊button1,將取到的波特率顯示到textBox1中。
完整代碼如下:
1 using System; 2 using System.CodeDom; 3 using System.Collections.Generic; 4 using System.ComponentModel; 5 using System.Data; 6 using System.Drawing; 7 using System.IO; 8 using System.Linq; 9 using System.Runtime.InteropServices; 10 using System.Text; 11 using System.Threading.Tasks; 12 using System.Windows.Forms; 13 14 namespace WindowsFormsApplication1 15 { 16 public partial class Form1 : Form 17 { 18 public Form1() 19 { 20 InitializeComponent(); 21 } 22 23 24 [DllImport("kernel32")] 25 // 讀配置文件方法的6個參數:所在的分區(section)、鍵值、 初始缺省值、 StringBuilder、 參數長度上限、配置文件路徑 26 private static extern int GetPrivateProfileString(string section, string key, string deVal, StringBuilder retVal, 27 int size, string filePath); 28 29 [DllImport("kernel32")] 30 // 寫配置文件方法的4個參數:所在的分區(section)、 鍵值、 參數值、 配置文件路徑 31 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); 32 33 public static void SetValue(string section, string key, string value) 34 { 35 //獲得當前路徑,當前是在Debug路徑下 36 string strPath = Environment.CurrentDirectory + "\\system.ini"; 37 WritePrivateProfileString(section, key, value, strPath); 38 } 39 40 public static string GetValue(string section, string key) 41 { 42 StringBuilder sb = new StringBuilder(255); 43 string strPath = Environment.CurrentDirectory + "\\system.ini"; 44 //最好初始缺省值設置為非空,因為如果配置文件不存在,取不到值,程序也不會報錯 45 GetPrivateProfileString(section, key, "配置文件不存在,未取到參數", sb, 255, strPath); 46 return sb.ToString(); 47 48 } 49 50 private void Form1_Load(object sender, EventArgs e) 51 { 52 SetValue("參數","波特率","9600"); 53 } 54 55 private void button1_Click(object sender, EventArgs e) 56 { 57 textBox1.Text = GetValue("參數", "波特率"); 58 } 59 60 61 62 } 63 }
程序界面: