通过Window API kernel32.dll读写INI文件

public class IniFile
    {
        [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 string GetFileName
        {
            get;
            set;
        }
        public IniFile(string filePath)
        {
            GetFileName = filePath;
        }
        ///


        /// 写入INI文件
        ///

        ///
        ///
        ///
        public void WriteValue(string Section, string key, string value)
        {
            WritePrivateProfileString(Section, key, value, GetFileName);
        }
        ///
        /// 读取INI文件
        ///

        ///
        /// 待获取数据的键
        /// 表示当通过键获取数据时,如果键不存在或无法找到数据,则返回该值
        ///
        public string ReadValue(string Section, string key, string defValue)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, key, defValue, temp, 255, this.GetFileName);
            return temp.ToString();
        }
    }

应用:

 

 public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        IniFile ini = new IniFile("C:\\config.ini");
        private void button1_Click(object sender, EventArgs e)
        {
            ini.WriteValue("Config", "Port", "COM1");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string port = ini.ReadValue("Config", "Port", "COM2");
        }
    }

结果:

写入:

[Config]
Port=COM1

 

读出:

COM1, 

假如我改成这样: string port = ini.ReadValue("Config", "Port123", "COM2");,该Port123键不存在INI文件中,那么port的值就为COM2


 

你可能感兴趣的:(通过Window API kernel32.dll读写INI文件)