C#读取INI文件

原文:C#读取INI文件

摘自:伊图教程网

http://www.etoow.com/html/2007-08/1187271505-1.html
       虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。

       INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)

[Section]

Key=Value

       VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面是一个C# ini文件读写类,从网上收集的,很全,就是没有对section的改名功能,高手可以增加一个。

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections;
using System.Collections.Specialized;

namespace wuyisky
{
    /// <summary>
    /// IniFiles的类
    /// </summary>
    public class IniFiles
    {
        public string FileName; //INI文件名
        //声明读写INI文件的API函数
        [DllImport("kernel32")]
        private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);
        //类的构造函数,传递INI文件名
        public IniFiles(string AFileName)
        {
            // 判断文件是否存在
            FileInfo fileInfo = new FileInfo(AFileName);
            //Todo:搞清枚举的用法
            if ((!fileInfo.Exists))
            { //|| (FileAttributes.Directory in fileInfo.Attributes))
                //文件不存在,建立文件
                System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default);
                try
                {
                    sw.Write("#表格配置档案");
                    sw.Close();
                }
                catch
                {
                    throw (new ApplicationException("Ini文件不存在"));
                }
            }
            //必须是完全路径,不能是相对路径
            FileName = fileInfo.FullName;
        }
        //写INI文件
        public void WriteString(string Section, string Ident, string Value)
        {
            if (!WritePrivateProfileString(Section, Ident, Value, FileName))
            {
                throw (new ApplicationException("写Ini文件出错"));
            }
        }
        //读取INI文件指定
        public string ReadString(string Section, string Ident, string Default)
        {
            Byte[] Buffer = new Byte[65535];
            int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName);
            //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
            string s = Encoding.GetEncoding(0).GetString(Buffer);
            s = s.Substring(0, bufLen);
            return s.Trim();
        }

        //读整数
        public int ReadInteger(string Section, string Ident, int Default)
        {
            string intStr = ReadString(Section, Ident, Convert.ToString(Default));
            try
            {
                return Convert.ToInt32(intStr);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Default;
            }
        }

        //写整数
        public void WriteInteger(string Section, string Ident, int Value)
        {
            WriteString(Section, Ident, Value.ToString());
        }

        //读布尔
        public bool ReadBool(string Section, string Ident, bool Default)
        {
            try
            {
                return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default)));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Default;
            }
        }

        //写Bool
        public void WriteBool(string Section, string Ident, bool Value)
        {
            WriteString(Section, Ident, Convert.ToString(Value));
        }

        //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中
        public void ReadSection(string Section, StringCollection Idents)
        {
            Byte[] Buffer = new Byte[16384];
            //Idents.Clear();

            int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0),
                  FileName);
            //对Section进行解析
            GetStringsFromBuffer(Buffer, bufLen, Idents);
        }

        private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings)
        {
            Strings.Clear();
            if (bufLen != 0)
            {
                int start = 0;
                for (int i = 0; i < bufLen; i++)
                {
                    if ((Buffer[i] == 0) && ((i - start) > 0))
                    {
                        String s = Encoding.GetEncoding(0).GetString(Buffer, start, i - start);
                        Strings.Add(s);
                        start = i + 1;
                    }
                }
            }
        }
        //从Ini文件中,读取所有的Sections的名称
        public void ReadSections(StringCollection SectionList)
        {
            //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section
            byte[] Buffer = new byte[65535];
            int bufLen = 0;
            bufLen = GetPrivateProfileString(null, null, null, Buffer,
             Buffer.GetUpperBound(0), FileName);
            GetStringsFromBuffer(Buffer, bufLen, SectionList);
        }
        //读取指定的Section的所有Value到列表中
        public void ReadSectionValues(string Section, NameValueCollection Values)
        {
            StringCollection KeyList = new StringCollection();
            ReadSection(Section, KeyList);
            Values.Clear();
            foreach (string key in KeyList)
            {
                Values.Add(key, ReadString(Section, key, ""));
            }
        }
        ////读取指定的Section的所有Value到列表中,
        //public void ReadSectionValues(string Section, NameValueCollection Values,char splitString)
        //{  string sectionValue;
        //  string[] sectionValueSplit;
        //  StringCollection KeyList = new StringCollection();
        //  ReadSection(Section, KeyList);
        //  Values.Clear();
        //  foreach (string key in KeyList)
        //  {
        //    sectionValue=ReadString(Section, key, "");
        //    sectionValueSplit=sectionValue.Split(splitString);
        //    Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString());

        //  }
        //}
        //清除某个Section
        public void EraseSection(string Section)
        {
            if (!WritePrivateProfileString(Section, null, null, FileName))
            {
                throw (new ApplicationException("无法清除Ini文件中的Section"));
            }
        }
        //删除某个Section下的键
        public void DeleteKey(string Section, string Ident)
        {
            WritePrivateProfileString(Section, Ident, null, FileName);
        }
        //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
        //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
        //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
        public void UpdateFile()
        {
            WritePrivateProfileString(null, null, null, FileName);
        }

        //检查某个Section下的某个键值是否存在
        public bool ValueExists(string Section, string Ident)
        {
            StringCollection Idents = new StringCollection();
            ReadSection(Section, Idents);
            return Idents.IndexOf(Ident) > -1;
        }

        //确保资源的释放
        ~IniFiles()
        {
            UpdateFile();
        }
    }
}

目前C# 对ini文件操作基本上要被xml文件取代了,但是我觉得ini文件的读写仍然是编程的基本,是必须会的

时间: 2024-08-08 03:43:23

C#读取INI文件的相关文章

VB.NET中读取INI文件设置信息函数sdGetIniInfo

函数 虽然VB.NET中读取XML配置信息很方便,但有时开发的过程中还是要用到INI文件,在VB.NET中读取INI却不像VB中那么方便了,刚才写了个函数,现贴出来,也许各位能用得上.     '函数名: sdGetIniInfo    '功能:读取INI文件设置信息    '参数说明:iniFile-->INI文件     iniSection--INI文件中设置的部分名称    '作者:SD    '日期:2005-10-11    'Email:ztqas@126.com    '备注:转

使用正则表达式(regex_replace)模拟读取INI文件

废话不多说了,直接给大家贴代码了,具体代码如下所示: #include "stdio.h" #include <sstream> #include <iostream> #include <fstream> #include <regex> using namespace std; void Trim(char * str); void lTrim(char * str); void rTrim(char * str); // 测试ssc

关于C#读取INI文件出现的问题

问题描述 usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Runtime.InteropServices;usingSystem.Data.SqlClient;usingSystem.Data;namespacedblink{publicclassClass1{[DllImport("kernel32")]privatestaticexternlongWr

Python读取ini文件、操作mysql、发送邮件实例_python

我是闲的没事干,2014过的太浮夸了,博客也没写几篇,哎~~~ 用这篇来记录即将逝去的2014 python对各种数据库的各种操作满大街都是,不过,我还是喜欢我这种风格的,涉及到其它操作,不过重点还是对数据库的操作.呵~~ Python操作Mysql 首先,我习惯将配置信息写到配置文件,这样修改时可以不用源代码,然后再写通用的函数供调用 新建一个配置文件,就命名为conf.ini,可以写各种配置信息,不过都指明节点(文件格式要求还是较严格的): 复制代码 代码如下: [app_info] DAT

C# 读取INI文件数据问题

问题描述 现在我可以读取INI文件里面的数据,可是我现在想具体到某个数据该怎么做.比如配置是[Setting]ChannelNo1DataEnabled=trueChannelNo1ScopeMode=02ChannelNo1Scope=01ChannelNo1countMode=01ChannelNo1LoadMode=01ChannelNo2DataEnabled=trueChannelNo2ScopeMode=02ChannelNo2Scope=01ChannelNo2countMode=

分享用Python通过读取ini文件操作mysql来发送邮件实例

Python操作Mysql 首先,我习惯将配置信息写到配置文件,这样修改时可以不用源代码,然后再写通用的函数供调用 新建一个配置文件,就命名为conf.ini,可以写各种配置信息,不过都指明节点(文件格式要求还是较严格的):  代码如下 复制代码 [app_info] DATABASE=test USER=app PASSWORD=123456 HOST=172.17.1.1 PORT=3306 [mail] host=smtp.163.com mail_from=zhoujie0111@126

vb建立与读取.ini文件

虽然进入win95之後,一般读写ini文件被读写Registry所取代,但我们还是可以透过win31的传统方式读写ini文件,以存程式目前的相关设定,而於下一次程式执行时再读回来.目前建议使用GetSetting SaveSetting的方式存於Registry中,不用目前的方式.储存程式的设定 '请於form中放3个TextBox,一个CommandBox Private Declare Function GetPrivateProfileString Lib "kernel32"

为怎么用GetPrivateProfileInt无法读取INI文件数据,

问题描述 出现"从字符串"TextBox1"到类型"Integer"的强制转换无效."错误,是那里错了呢?---------------------------------------------------------------------PrivateSubForm1_Load(ByValsenderAsSystem.Object,ByValeAsSystem.EventArgs)HandlesMyBase.LoadTextBox1.Tex

java 通过 Properties类 读取ini文件 键—值对

  /* Properties  类  利用 System的getProerties返回系统属性 传递一个 System.out 这个类的用处是可以读取一个 ini配置文件的信息   键=值  具体用法看docs */ import java.util.* ; import java.io.* ;  //FileInputStream  在这个包中 class  PropTest {  public static void main(String []args)  {   /*Propertie