using System; using System.Runtime.InteropServices; using System.Text; using System.IO; namespace Ant.Service.Utilities { /// /// INI文件读写类。 /// public class INIClass { public string inipath; [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); /// /// 构造方法 /// /// 文件路径 public INIClass(string INIPath) { inipath = INIPath; } /// /// 写入INI文件 /// /// 项目名称(如 [TypeName] ) /// 键 /// 值 public void IniWriteValue(string Section, string Key, string Value) { WritePrivateProfileString(Section, Key, Value, this.inipath); } /// /// 读出INI文件 /// /// 项目名称(如 [TypeName] ) /// 键 public string IniReadValue(string Section, string Key) { StringBuilder temp = new StringBuilder(500); int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath); return temp.ToString(); } /// /// 验证文件是否存在 /// /// 布尔值 public bool ExistINIFile() { return File.Exists(inipath); } /// /// ///创建文件夹 /// /// ///路径 /// private void NewDirectory(String path) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } /// /// 添加一行注释 /// /// 注释 public void AddNotes(string Notes) { string filename = inipath; string path; path = Directory .GetParent(filename).ToString(); NewDirectory(path); FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine(@";" + Notes); sw.Flush(); sw.Close(); fs.Close(); sw.Dispose(); fs.Dispose(); } /// /// 添加一行文本 /// /// 文本 public void AddText(string Text) { string filename = inipath; string path; path = Directory .GetParent(filename).ToString(); NewDirectory(path); FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); sw.BaseStream.Seek(0, SeekOrigin.End); sw.WriteLine(Text); sw.Flush(); sw.Close(); fs.Close(); sw.Dispose(); fs.Dispose(); } } }