C# 操作INI文件的类(支持中文)

本文介绍了一个使用C#编写的CIniFile类,该类提供了读取和写入INI文件的强大功能。包括读写字符串、整数、布尔值、浮点数和日期等不同类型的数据,还支持检查节和值的存在状态、删除特定项或整个节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在同事帮助下奋斗了一两天,终于可以用了。Win32 下还是Delphi好用!还是习惯Delphi的private, protected, public 分类。老顽固了,:D

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

namespace IniFile
{
    /// <CopyRight>
    /// tobelost@gmail.com
    /// Nov 08, 2007
    /// </CopyRight>
    public class CIniFile
    {
        public CIniFile(string AFullFileName)
        {
            FFullFileName = AFullFileName;
        }
        #region Private
            private const int n_StrSize = 1024;
            private const int n_SecSize = 32768;
            private const int n_KeySize = 256;
            private string FFullFileName;
        #endregion

        #region Protected
            protected bool FileAssigned()
            {
                return !string.IsNullOrEmpty(FFullFileName) &&
                       File.Exists(FFullFileName);
            }

            #region API declaration
            [DllImport("kernel32")]  // 0 = fail
            protected static extern long WritePrivateProfileString(
                string ASection, string AKey, string AVal, string AFileName);

            [DllImport("kernel32")]  // returns the length
            protected static extern long GetPrivateProfileString(
                string ASection, string AKey, string ADefault, StringBuilder ARetVal, uint ASize, string AFileName);

            [DllImport("kernel32")] // returns the length
            protected static extern long GetPrivateProfileSectionNames(
                byte[] ANames, uint ABuffSize, string AFileName);

            [DllImport("kernel32")] // returns the length
            protected static extern int GetPrivateProfileSection(
                string ASection, byte[] AContents, int ABuffSize, string AFileName);
            #endregion
        #endregion

        #region Public
            #region Read
            public virtual string ReadString(string ASection, string AKey, string ADefault)
            {
                if (!FileAssigned())
                    return ADefault;

                StringBuilder sbTemp = new StringBuilder(n_StrSize);
                if (GetPrivateProfileString(ASection, AKey, ADefault, sbTemp, n_StrSize, FFullFileName) > 0)
                {
                    return sbTemp.ToString();
                }
                else
                {
                    return ADefault;
                }
            }
            public virtual int ReadInt(string ASection, string AKey, int ADefault)
            {
                string intStr = ReadString(ASection, AKey, "");
                try
                {
                    return int.Parse(intStr);
                }
                catch (InvalidCastException)
                {
                    return ADefault;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            public virtual bool ReadBool(string ASection, string AKey, bool ADefault)
            {
                int blnVal = ReadInt(ASection, AKey, Convert.ToInt32(ADefault));
                return (blnVal != 0);
            }
            public virtual double ReadDouble(string ASection, string AKey, double ADefault)
            {
                string dblStr = ReadString(ASection, AKey, "");
                try
                {
                    return Convert.ToDouble(dblStr);
                }
                catch (InvalidCastException)
                {
                    return ADefault;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            public virtual DateTime ReadDateTime(string ASection, string AKey, DateTime ADefault)
            {
                string dtStr = ReadString(ASection, AKey, "");
                try
                {
                    return Convert.ToDateTime(dtStr);
                }
                catch(InvalidCastException)
                {
                    return ADefault;
                }
                catch(Exception ex)
                {
                    throw ex;
                }
            }
            #endregion

            #region Write
            public virtual bool WriteString(string ASection, string AKey, string AValue)
            {
                if (!FileAssigned())
                    return false;

                long R = WritePrivateProfileString(ASection, AKey, AValue, FFullFileName);
                return (R > 0);
            }
            public virtual bool WriteInt(string ASection, string AKey, int AValue)
            {
                return WriteString(ASection, AKey, Convert.ToString(AValue));
            }
            public virtual bool WriteBool(string ASection, string AKey, bool AValue)
            {
                string[] blnValues = {"0", "1"};
                return WriteString(ASection, AKey, blnValues[Convert.ToInt32(AValue)]);
            }
            public virtual bool WriteDouble(string ASection, string AKey, double AValue)
            {
                return WriteString(ASection, AKey, Convert.ToString(AValue));
            }
            public virtual bool WriteDateTime(string ASection, string AKey, DateTime AValue)
            {
                return WriteString(ASection, AKey, Convert.ToString(AValue));
            }
            #endregion

            #region Management
            public virtual bool SectionExists(string ASection)
            {
                if (!FileAssigned())
                    return false;

                StringCollection names;
                if (ReadSectionNames(out names))
                {
                    return names.IndexOf(ASection) > -1;
                }
                else
                {
                    return false;
                }
            }
            public virtual bool ValueExists(string ASection, string AKey)
            {
                if (!FileAssigned())
                    return false;

                StringCollection keys;
                if (ReadSectionKeys(ASection, out keys))
                {
                    return keys.IndexOf(AKey) > -1;
                }
                else
                {
                    return false;
                }
            }
            public virtual void DeleteKey(string ASection, string AKey)
            {
                if (!FileAssigned())
                    return;

                long retVal = WritePrivateProfileString(ASection, AKey, null, FFullFileName);
                if (retVal == 0)
                {
                    throw new IOException(string.Format("Unable to write to {0}", FFullFileName));
                }
            }
            public virtual void EraseSection(string ASection)
            {
                if (!FileAssigned())
                    return;

                long retVal = WritePrivateProfileString(ASection, null, null, FFullFileName);
                if (retVal == 0)
                {
                    throw new IOException(string.Format("Unable to write to {0}", FFullFileName));
                }   
            }
            // Reads all section names.
            public virtual bool ReadSectionNames(out StringCollection ASectionNames)
            {
                ASectionNames = new StringCollection();
                if (!FileAssigned())
                    return false;

                byte[] buff = new byte[n_SecSize];
                long retCnt = GetPrivateProfileSectionNames(buff, n_SecSize, FFullFileName);
                if (retCnt > 0)
                {
                    int iPos = 0;
                    for (int iCnt = 0; iCnt < retCnt; iCnt++)
                    {
                        if (buff[iCnt] == 0)
                        {
                            string name = ASCIIEncoding.Default.GetString(buff, iPos, iCnt).Trim();
                            iPos = iCnt + 1;
                            if (!string.IsNullOrEmpty(name))
                            {
                                ASectionNames.Add(name);
                            }
                        }
                    }
                    return ASectionNames.Count > 0;
                }
                else
                {
                    return false;
                }
            }
            // Reads all contents of a specified section.
            public virtual bool ReadSectionContents(string ASection, out StringCollection AContents)
            {
                AContents = new StringCollection();
                if (!FileAssigned())
                    return false;

                byte[] buff = new byte[n_KeySize];              
                int retCnt = GetPrivateProfileSection(ASection, buff, n_KeySize, FFullFileName);
                if (retCnt > 0)
                {
                    int iPos = 0;
                    for (int iCnt = 0; iCnt < retCnt; iCnt++)
                    {
                        if (buff[iCnt] == 0)
                        {
                            string key = ASCIIEncoding.Default.GetString(buff, iPos, iCnt).Trim();
                            iPos = iCnt + 1;
                            if (!string.IsNullOrEmpty(key))
                            {
                                AContents.Add(key);
                            }
                        }
                    }
                    return AContents.Count > 0;
                }
                else
                {
                    return false;
                }
            }
            // Reads all keys of a specified section.
            public virtual bool ReadSectionKeys(string ASection, out StringCollection AKeys)
            {
                AKeys = new StringCollection();
                if (!FileAssigned())
                    return false;

                if (ReadSectionContents(ASection, out AKeys))
                {
                    for (int i = 0; i < AKeys.Count; i++)
                    {
                        string sKey = AKeys[i];
                        int iPos = sKey.IndexOf("=");
                        AKeys[i] = sKey.Substring(0, iPos);
                    }
                    return AKeys.Count > 0;
                }
                else
                {
                    return false;
                }
            }
            // Reads all values of a specified section.
            public virtual bool ReadSectionValues(string ASection, out StringCollection AValues)
            {
                AValues = new StringCollection();
                if (!FileAssigned())
                    return false;

                if (ReadSectionContents(ASection, out AValues))
                {
                    for (int i = 0; i < AValues.Count; i++)
                    {
                        string sValue = AValues[i];
                        int iPos = sValue.IndexOf("=");
                        AValues[i] = sValue.Substring(iPos + 1);
                    }
                    return AValues.Count > 0;
                }
                else
                {
                    return false;
                }
            }
            #endregion
        #endregion
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值