C# ini 文件解析库

大兔子大兔子 提交于 2019-11-29 22:10:43

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;
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!