• 通过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;
            }
            /// <summary>
            /// 写入INI文件
            /// </summary>
            /// <param name="Section"></param>
            /// <param name="key">键</param>
            /// <param name="value">值</param>
            public void WriteValue(string Section, string key, string value)
            {
                WritePrivateProfileString(Section, key, value, GetFileName);
            }
            /// <summary>
            /// 读取INI文件
            /// </summary>
            /// <param name="Section"></param>
            /// <param name="key">待获取数据的键</param>
            /// <param name="defValue">表示当通过键获取数据时,如果键不存在或无法找到数据,则返回该值</param>
            /// <returns></returns>
            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


     

  • 相关阅读:
    SL版优酷蛋幕视频基本组成(一)
    C++符号优先级
    静态与非静态对程序效率的影响
    SQLite语法备忘录
    优酷
    通过终端,查看SQLITE3的存储文件
    ASP.NET (C#开发环境)Request对象 之 ServerVariables集合
    SQL高级查询
    SQL Server定时执行SQL语句
    保存Session不过期和web.config 中SessionState的配置
  • 原文地址:https://www.cnblogs.com/KimhillZhang/p/2689833.html
Copyright © 2020-2023  润新知