ini 文件操作

18 篇文章 0 订阅

做了一些修改,见类:

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

namespace INIStream
{
    /// <summary>
    /// 一个模仿Delphi的TIniFile的类
    /// 修订:1.1 修正了对中文系统的支持。
    /// 1.2 增加了UpdateFile方法,实现了对Win9x的支持
    /// 1.3 增加了读写布尔,整数的操作
    /// 1.4 修正了写Ini虽然成功,但是会抛出异常的错误
    /// 1.5 ReadString返回的是Trim后的字符串
    /// 1.6 统一并扩大了读写缓冲区的大小
    /// </summary>
    public class IniFile
    {
        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 IniFile(string AFileName)
        {
            // 判断文件是否存在
            FileInfo fileInfo = new FileInfo(AFileName);
            //Todo:搞清枚举的用法
            if ((!fileInfo.Exists)) //|| (FileAttributes.Directory in fileInfo.Attributes))
                throw (new ApplicationException("Ini文件不存在"));
            //必须是完全路径,不能是相对路径
            FileName = fileInfo.FullName;
        }
        #region 读
        
        /// <summary>
        /// 读取INI文件指定
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="key">键</param>
        /// <param name="Default">默认值</param>
        /// <returns></returns>
        private string Read(string Section, string key, string Default)
        {
            Byte[] Buffer = new Byte[65535];
            int bufLen = GetPrivateProfileString(Section, key, "", Buffer, Buffer.GetUpperBound(0), FileName);
            //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文
            string s = Encoding.GetEncoding(0).GetString(Buffer);
            s = s.Substring(0, bufLen);
            return s.Trim();
        }

        public string ReadString(string Section, string key) {
            return Read(Section, key, "");
        }

        /// <summary>
        /// 读整数
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="key">键</param>
        /// <returns></returns>
        public int ReadInteger(string Section, string key)
        {
            int Default = -1;
            string intStr = Read(Section, key, Default.ToString());
            try
            {
                return Convert.ToInt32(intStr);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Default;
            }
        }


        /// <summary>
        /// 读布尔
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="key">键</param>
        /// <returns></returns>
        public bool ReadBool(string Section, string key)
        {
            bool Default = false;
            try
            {
                return Convert.ToBoolean(Read(Section, key, Convert.ToString(Default)));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return Default;
            }
        }

        /// <summary>
        /// 从Ini文件中,将指定的Section名称中的所有key添加到列表中
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="keys">集合</param>
        public void ReadSection(string Section, StringCollection keys)
        {
            Byte[] Buffer = new Byte[16384];
            //keys.Clear();

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

        /// <summary>
        /// 从Ini文件中,读取所有的Sections的名称
        /// </summary>
        /// <param name="SectionList">节点集合</param>
        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);
        }

        /// <summary>
        /// 读取指定的Section的所有Value到列表中
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="Values"></param>
        public void ReadSectionValues(string Section, NameValueCollection Values)
        {
            StringCollection KeyList = new StringCollection();
            ReadSection(Section, KeyList);
            Values.Clear();
            foreach (string key in KeyList)
            {
                Values.Add(key, Read(Section, key, ""));
            }
        }
        #endregion

        #region 写
        /// <summary>
        /// 写INI文件
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="key">键</param>
        /// <param name="Value">值</param>
        public void WriteValue(string Section, string key, string Value)
        {
            if (!WritePrivateProfileString(Section, key, Value, FileName))
            {
                // Todo:抛出自定义的异常
                throw (new ApplicationException("写Ini文件出错"));
            }
        }

        #endregion
        
        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;
                    }
                }
            }
        }
        
        /// <summary>
        /// 清除某个Section
        /// </summary>
        /// <param name="Section">节点</param>
        public void EraseSection(string Section)
        {
            //
            if (!WritePrivateProfileString(Section, null, null, FileName))
            {
                throw (new ApplicationException("无法清除Ini文件中的Section"));
            }
        }
        /// <summary>
        /// 删除某个Section下的键
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="key">键</param>
        public void DeleteKey(string Section, string key)
        {
            WritePrivateProfileString(Section, key, null, FileName);
        }

        //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件
        //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile
        //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。
        private void UpdateFile()
        {
            WritePrivateProfileString(null, null, null, FileName);
        }

        /// <summary>
        /// 检查某个Section下的某个键值是否存在
        /// </summary>
        /// <param name="Section">节点</param>
        /// <param name="key">键</param>
        /// <returns></returns>
        public bool ValueExists(string Section, string key)
        {
            StringCollection keys = new StringCollection();
            ReadSection(Section, keys);
            return keys.IndexOf(key) > -1;
        }

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值