读写Ini文件

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;


namespace F.Studio.Common.Cfg
{
    public class INIHelper
    {
        public string FilePath { get; private set; }
        [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);

        //声明读写INI文件的API函数   
        public INIHelper(string filePath)
        {

            FilePath = filePath;
        }
        public static string AppPath
        {
            get
            {
                return System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 
            }
        }
        //类的构造函数,传递INI文件名
        public void SetValue(string Section, string Key, string Value)
        {
            WritePrivateProfileString(Section, Key, Value, this.FilePath);
        }

        //写INI文件 

        public string GetValue(string Section, string Key, string def)
        {
            StringBuilder temp = new StringBuilder(255);

            int i = GetPrivateProfileString(Section, Key, def, temp, 255, this.FilePath);

            return temp.ToString();

        }


    }
}

调整了根据dll文件位置获取ini文件的位置,以适应pb等调试环境下执行

----------------------------------------------------------------------

使用方式

        private Lazy<string> LazyConn = new Lazy<string>(() =>
        {
            var filename = INIHelper.AppPath + "/settings.ini";
            var iniHelper = new INIHelper(filename);
            return iniHelper.GetValue("Connections", "ConnStr", "");
        }, true);

原文地址:https://www.cnblogs.com/wdfrog/p/3001967.html