using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace Audit.ViewModel { public class ReadIni { /// /// 为INI文件中指定的节点取得字符串 /// /// 欲在其中查找关键字的节点名称 /// 欲获取的项名 /// 指定的项没有找到时返回的默认值 /// 指定一个字串缓冲区,长度至少为nSize /// 指定装载到lpReturnedString缓冲区的最大字符数量 /// INI文件完整路径 /// 复制到lpReturnedString缓冲区的字节数量,其中不包括那些NULL中止字符 [DllImport("kernel32")] private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName); /// /// 修改INI文件中内容 /// /// 欲在其中写入的节点名称 /// 欲设置的项名 /// 要写入的新字符串 /// INI文件完整路径 /// 非零表示成功,零表示失败 [DllImport("kernel32")] private static extern int WritePrivateProfileString(string lpApplicationName, string lpKeyName, string lpString, string lpFileName); public static string ReadIniData(string section, string key, string def, string filePath)//读取INI文件 { StringBuilder sb = new StringBuilder(1024); GetPrivateProfileString(section, key, def, sb, 1024, filePath); return sb.ToString(); } /// /// 写INI文件值 /// /// 欲在其中写入的节点名称 /// 欲设置的项名 /// 要写入的新字符串 /// INI文件完整路径 /// 非零表示成功,零表示失败 public static int WriteData(string section, string key, string value, string filePath) { return WritePrivateProfileString(section, key, value, filePath); } /// /// 删除节 /// /// 节点名 /// INI文件完整路径 /// 非零表示成功,零表示失败 public static int DeleteSection(string section, string filePath) { return WriteData(section, null, null, filePath); } /// /// 删除键的值 /// /// 节点名 /// 键名 /// INI文件完整路径 /// 非零表示成功,零表示失败 public static int DeleteKey(string section, string key, string filePath) { return WriteData(section, key, null, filePath); } } }