C#之构建配置文件实现获取并保存功能

实现工具类,会创建一个Config.ini的配置文件

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace ConfigUtil
{
    class ConfigUtils
    {
        #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);

        [DllImport("kernel32")]
        public static extern int GetPrivateProfileInt(string lpApplicationName, string lpKeyName, int nDefault, string lpFileName);


        #endregion

        #region 读Ini文件
        //Section参数、Key参数和IniFilePath不用再说,Value参数表明key的值,
        //而这里的NoText对应API函数的def参数,它的值由用户指定,是当在配置文件中没有找到具体的Value时,就用NoText的值来代替。
        //NoText 可以为null或""
        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }
        public static string ReadIni(string Section, string Key, string NoText)
        {
            return ReadIniData(Section, Key, NoText, ".\\Config\\Config.ini");
        }
        #endregion

        #region 写Ini文件

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                if (OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        public static bool WritrIni(string Section, string Key, string Value)
        {
            return WriteIniData(Section, Key, Value, ".\\Config\\Config.ini");
        }
        #endregion
    }
}

  

文件的内容样式如下

[TEST]
test=123

  

具体的实现,下列是读取的引用

string test = ConfigUtils.ReadIni("TEST", "test", "");

  

写入的方式如下

ConfigUtils.WritrIni("TEST", "test", "123");

  

 

posted @ 2024-07-16 19:28  无产铁锤  阅读(33)  评论(0)    收藏  举报