C#读写ini文件(类文件)

来源:互联网 发布:54 80坐标系转换软件 编辑:程序博客网 时间:2024/06/06 06:37

已下是已经写好的读写INI文件的类:

using System.Runtime.InteropServices;
using System.Text;
using System.IO;
namespace ReadWriteINI
{
    ///  <summary>
    ///  读写ini文件的类
    ///  调用kernel32.dll中的两个api:WritePrivateProfileString,GetPrivateProfileString来实现对ini  文件的读写。
    ///
    ///  INI文件是文本文件,
    ///  由若干节(section)组成,
    ///  在每个带括号的标题下面,
    ///  是若干个关键词(key)及其对应的值(value)
    /// 
    ///[Section]
    ///Key=value
    ///
    ///  </summary>
    public class IniFile
    {
        ///  <summary>
        ///  ini文件名称(带路径)
        ///  </summary>
        public string filePath;

        //声明读写INI文件的API函数
        [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);

        ///  <summary>
        ///  类的构造函数
        ///  </summary>
        ///  <param  name="INIPath">INI文件名</param> 
        public IniFile(string INIPath)
        {
            filePath = INIPath;
        }

        ///  <summary>
        ///   写INI文件
        ///  </summary>
        ///  <param  name="Section">Section</param>
        ///  <param  name="Key">Key</param>
        ///  <param  name="value">value</param>
        public void WriteInivalue(string Section, string Key, string value)
        {
            WritePrivateProfileString(Section, Key, value, this.filePath);

        }

        ///  <summary>
        ///    读取INI文件指定部分
        ///  </summary>
        ///  <param  name="Section">Section</param>
        ///  <param  name="Key">Key</param>
        ///  <returns>String</returns> 
        public string ReadInivalue(string Section, string Key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.filePath);
            return temp.ToString();

        }

        /// <summary>
        /// 清空ini文件
        /// </summary>
        public void ClearIniValue()
        {
            StreamWriter sw = new StreamWriter(this.filePath, false, Encoding.ASCII);
            sw.Close();
        }
    }
}

 

调用:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ReadWriteINI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IniFile aa = new IniFile(@"此处填写您的计算机中保存的ini文件路径。没有请创建内容为空的ini文件");
  
            aa.WriteInivalue("1", "2", "3");

            textBox1.Text = aa.ReadInivalue("1", "2");
        }
    }
}

0 0