C#读写配置文件

直接添加一个Confighelper类文件,将下面的复制进去

class Confighelper
    {
        [DllImport("kernel32")]
        private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filepath);
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filepath);
        /// 
        /// 读配置文件
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static String ReadIni(string section, string key, string def, int size, string filepath)
        {
            StringBuilder sb = new StringBuilder();
            GetPrivateProfileString(section, key, def, sb, size, filepath);
            return sb.ToString();
        }
        /// 
        /// 写入数据到配置文件
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public static long WriteIni(string section, string key, string val, string filepath)
        {
            return WritePrivateProfileString(section, key, val, filepath);
        }
        // 删除ini文件下所有段落
        public void ClearAllSection(string filepath)
        {
            WriteIni(null, null, null, filepath);
        }
        //删除ini文件下personal段落下的所有键
        public void ClearSection(string Section, string filepath)
        {
            WriteIni(Section, null, null, filepath);
        }
    }

 例如将combox中的内容写入配置文档中

 private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "/config.ini";//配置文档的存放地址
            Confighelper.WriteIni("COM", "text", comboBox1.Text, path);//写入配置文档
        }

 如何读取配置文件的内容

 private void Form1_Load(object sender, EventArgs e)
        {

            string path = Application.StartupPath + "/config.ini";
            comboBox1.Text = Confighelper.ReadIni("COM", "text", "", 1024, path);//读取配置文档
            comboBox2.Text = Confighelper.ReadIni("波特率", "text", "", 1024, path);
            comboBox3.Text = Confighelper.ReadIni("数据位", "text", "", 1024, path);
            comboBox4.Text = Confighelper.ReadIni("奇偶校验位", "text", "", 1024, path);
            comboBox5.Text = Confighelper.ReadIni("停止位", "text", "", 1024, path);
            Control.CheckForIllegalCrossThreadCalls = false;
        }

你可能感兴趣的:(C#,c#)