using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace JY.Utility { public class IniFileHelper { private static string iniFilePath = "ComConfig.ini"; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); public static string ReadIniData(string Section, string Key) { try { if (File.Exists(iniFilePath)) { StringBuilder temp = new StringBuilder(1024); GetPrivateProfileString(Section, Key, "", temp, 1024, iniFilePath); return temp.ToString(); } MessageBox.Show("节点:" + Section + ",键名:" + Key + ":读取配置文件错误!"); return null; } catch { throw; } } public static bool WriteIniData(string Section, string Key, string Value) { try { if (File.Exists(iniFilePath)) { if (WritePrivateProfileString(Section, Key, Value, iniFilePath) == 0L) { return false; } return true; } File.Create(iniFilePath).Close(); if (WritePrivateProfileString(Section, Key, Value, iniFilePath) == 0L) { return false; } return true; } catch { throw; } } public static void CreateIniFile(string StartupPath, string AppName) { iniFilePath = StartupPath + AppName; if (!Directory.Exists(StartupPath)) { Directory.CreateDirectory(StartupPath); } if (!File.Exists(iniFilePath)) { File.Create(iniFilePath).Close(); } } } }