ini檔為windows內常用來儲存setting的檔案,C#範例如下。
dllimport為必須要的,會動態連結到system32的檔案,
WritePrivateProfileString(string section, string key, string val, string filePath)寫入ini檔案
GetPrivateProfileString( string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString,uint nSize, string lpFileName)讀取ini檔案
P.S.此範例為自動抓取RS-232 port放入comboBox1內,尚未寫完,但讀寫ini的部分是完整的
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO.Ports;
namespace Test_INI
{
public partial class Form1 : Form
{
[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 Form1()
{
InitializeComponent();
string[] port_list = SerialPort.GetPortNames();
foreach (string port in port_list)
{
//MessageBox.Show("本機可用serial port: " + port); //測試用
comboBox1.Items.Add(port);
}
//當select port index換的時候 ,加入WritePrivateProfileString("Port Name", "name", 選擇的port
//string, @"D:\myConfig.ini");//寫入ini檔
WritePrivateProfileString("Port Name", "name", "COM1", @"D:\myConfig.ini");//寫入ini檔
WritePrivateProfileString("ModBus", "number", "1", @"D:\myConfig.ini");//寫入ini檔
WritePrivateProfileString("ModBus", "number", "2", @"D:\myConfig.ini");//寫入ini檔
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder data = new StringBuilder(255);
GetPrivateProfileString("Port Name", "name", "NA", data, 255,
@"D:\myConfig.ini");//section/key/def/ stringbuilder的變數/長度/路徑
MessageBox.Show(data.ToString());
}
}
}
沒有留言:
張貼留言