การตั้งคา config ที่ใช้ในโปรแกรมจาก file
1. สร้าง file สำหรับเก็บ config ต่าง ๆ ของโปรกแกรมก่อน
file name : config.ini
detail:
[DB]
MySQL_LOCAL = "DRIVER=MySQL ODBC 8.0 Unicode Driver;UID=root;PORT=3306;DATABASE=test_db;SERVER=localhost;PASSWORD=root_password"
MySQL_SERVER = "DRIVER=MySQL ODBC 8.0 Unicode Driver;UID=root;PORT=3306;DATABASE=test_db;SERVER=test_mysql.comPASSWORD=root_password"
[COM]
port1 = 1
port2 = 2
port3 = 3
baud = 115200
2. สร้าง function สำหรับค่า config จาก file
using System.Runtime.InteropServices;
/////////////////WINDWOS API//////////////////////////////////////////
internal static class NativeMethods
{
[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)]
internal static extern int GetPrivateProfileString(
string Section,
string Key,
string Default,
StringBuilder RetVal,
int Size,
string FilePath
);
}
/////////////////WINDWOS API//////////////////////////////////////////
/////////////////Function///////////////////////////////////////////////////////
public string PopValue(string section, string key)
{
StringBuilder sb = new StringBuilder(4096);
string FilePath = AppDomain.CurrentDomain.BaseDirectory + "config.ini";
int n = GetPrivateProfileString(section, key, "", sb, 4096, FilePath);
if (n < 1) return string.Empty;
return sb.ToString();
}
/////////////////Function///////////////////////////////////////////////////////
3. เรียกค่า config จาก file
string connStringLocal = PopValue("DB", "MySQL_LOCAL");
string connStringServer = PopValue("DB", "MySQL_SERVER");
int port1 = int.Parse(PopValue("RFID", "port1"));
int port2 = int.Parse(PopValue("RFID", "port2"));
int port3 = int.Parse(PopValue("RFID", "port3"));
- Log in to post comments
- 71 views