C# ini 文件解析库

来源:互联网 发布:win10控制软件安装 编辑:程序博客网 时间:2024/05/16 14:07

ini解析

因为需要使用C#进行ini 文件读写操作, 看到官方说解析ini文件需要使用xml读写库。感觉太过麻烦。因为先前有MFC 读写INI文件的经验,感觉API非常简单,所以稍微封装了一下。


代码

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Runtime.InteropServices;namespace IniFile{    class IniParser    {        [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 default_var, StringBuilder retVal, int buff_size, string filePath);        [DllImport("kernel32")]        private static extern int GetPrivateProfileInt(string section, string key, int default_var, string filePath);        private string _file_path;        public IniParser()        {            _file_path = Directory.GetCurrentDirectory()+"\\" +System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".ini";        }        public IniParser(string t_filename)        {            if (string.IsNullOrEmpty(t_filename))            {                _file_path = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".ini";                return;            }            else            {                _file_path = t_filename;            }        }        public bool writeData(string t_section, string t_key, string t_data)        /// if write data sucess , return true ,otherwise return false        {            long i_result = WritePrivateProfileString(t_section, t_key, t_data, _file_path);            return (i_result!=0?true:false);        }        public string readStringData(string t_section, string t_key, string t_default = "" )        /// if success , value would return , otherwise empty string return         {                      StringBuilder temp = new StringBuilder(255);            int i = GetPrivateProfileString(t_section, t_key, t_default, temp, 255, this._file_path);            return temp.ToString();                }        public int  readIntData(string  t_section, string t_key, int t_default =0)        {            int i_result = GetPrivateProfileInt(t_section, t_key, t_default, this._file_path);            return i_result;        }    }}
0 0