using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace Shentun.Utilities { public class IniFileHelper { #region API函数声明 [DllImport("kernel32")]//返回0表示失败,非0为成功 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); #endregion public static string Read(string filePath, string section, string key, string defaultValue) { if (File.Exists(filePath)) { section = section.Trim(); key = key.Trim(); defaultValue = defaultValue.Trim(); StringBuilder temp = new StringBuilder(1024); GetPrivateProfileString(section, key, defaultValue, temp, 1024, filePath); string returnValue = temp.ToString().Trim(); return returnValue; } else { throw new FileNotFoundException(filePath + "文件不存在"); } } public static void Write(string filePath, string section, string key, string value) { if (File.Exists(filePath)) { section = section.Trim(); key = key.Trim(); value = value.Trim(); StringBuilder temp = new StringBuilder(1024); long returnValue = WritePrivateProfileString(section, key, value, filePath); if (returnValue == 0) { throw new Exception("写入" + filePath + "文件数据失败"); } else { return; } } else { throw new FileNotFoundException(filePath + "文件不存在"); } } } }