调用windows系统文件,将C++库转为C# 函数
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
public class IniConfigHelper
{
#region API函数声明
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key,
string val, string filePath);
//需要调用GetPrivateProfileString的重载
[DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
private static extern long GetPrivateProfileString(string section, string key,
string def, StringBuilder retVal, int size, string filePath);
[DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
private static extern uint GetPrivateProfileStringA(string section, string key,
string def, Byte[] retVal, int size, string filePath);
#endregion
#region 读Ini文件
public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
return temp.ToString();
}
else return String.Empty;
}
#endregion
#region 写Ini文件
public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
{
long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
if (OpStation == 0)
return false;
else return true;
}
#endregion
}
}
using MS_Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DAL
{
//另外一个类,读取ModbusTCP的信息
public class SettingManager
{
public SettingManager(string path)
{
this.Path = path;
}
private string _path;
private ModbusTCPEntity iniSets;
public string Path { get => _path; set => _path = value; }
#region MyRegion
public ModbusTCPEntity LoadSysSettings()
{
try
{
iniSets = new ModbusTCPEntity
{
Ip = IniConfigHelper.ReadIniData("配置信息", "IP地址", "127.0.0.1", _path),
Port = IniConfigHelper.ReadIniData("配置信息", "端口号", "502", _path)
};
return iniSets;
}
catch (Exception)
{
return null;
}
}
public bool SaveSysSettings(ModbusTCPEntity iniSets)
{
bool result = true;
result &= IniConfigHelper.WriteIniData("配置信息", "IP地址", iniSets.Ip, _path);
result &= IniConfigHelper.WriteIniData("配置信息", "端口号", iniSets.Port, _path);
return result;
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MS_Entity
{
public class ModbusTCPEntity
{
public string Ip { get; set; }
public string Port { get; set; }
}
}
private static string FilePath = Application.StartupPath + "\\ConfigFile\\";
SettingManager IniManager = new SettingManager(FilePath + "MODBUSTCP_.ini");
CommonMethods.objModbusTCPEntity = IniManager.LoadSysSettings();