首页 > 系统相关 >Windows读写INI文件注意事项

Windows读写INI文件注意事项

时间:2022-11-10 10:33:45浏览次数:38  
标签:keyPairs String Windows 读写 INI sectionPair strLine null Section

GetPrivateProfileString最长读取65535个字符;
如果ini文件的Value值超过65535,GetPrivateProfileString读取会发生一些无法预料的错误;

WritePrivateProfileString理论上最长写入65535个字符,实际这个写入长度限制会有波动,尚不确定原因,建议不要太长;
1、调用WritePrivateProfileString写入超过65535长度,GetPrivateProfileString读取失败且不会返回默认值;
2、调用WritePrivateProfileString写入超过65535长度后手动修改ini文件,GetPrivateProfileString读取会发生一些无法预料的错误;

补充一:

写入65535个字符,GetPrivateProfileString成功读取65535个字符,返回值为65535;

写入65536个字符,GetPrivateProfileString读取失败,返回值为0;

写入65537个字符,GetPrivateProfileString读取失败,返回值为1;

扩展:

 public class IniParser
    {
        private Hashtable keyPairs = new Hashtable();
        private String iniFilePath;
        private struct SectionPair
        {
            public String Section;
            public String Key;
        }
        /// <summary>
        /// Opens the INI file at the given path and enumerates the values in the IniParser.
        /// </summary>
        /// <param name="iniPath">Full path to INI file.</param>
        public IniParser(String iniPath)
        {
            TextReader iniFile = null;
            String strLine = null;
            String currentRoot = null;
            String[] keyPair = null;
            iniFilePath = iniPath;
            if (File.Exists(iniPath))
            {
                try
                {
  
                    iniFile = new StreamReader(iniPath, Encoding.GetEncoding("GB2312"));
                    strLine = iniFile.ReadLine();
                    while (strLine != null)
                    {
                        strLine = strLine.Trim();
                            //.ToUpper();
                        if (strLine != "")
                        {
                            if (strLine.StartsWith("[") && strLine.EndsWith("]"))
                            {
                                currentRoot = strLine.Substring(1, strLine.Length - 2);
                            }
                            else
                            {
                                keyPair = strLine.Split(new char[] { '=' }, 2);
                                SectionPair sectionPair;
                                String value = null;
                                if (currentRoot == null)
                                    currentRoot = "ROOT";
                                sectionPair.Section = currentRoot;
                                sectionPair.Key = keyPair[0];
                                if (keyPair.Length > 1)
                                    value = keyPair[1];
                                keyPairs.Add(sectionPair, value);
                            }
                        }
                        strLine = iniFile.ReadLine();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (iniFile != null)
                        iniFile.Close();
                }
            }
            else
                throw new FileNotFoundException("Unable to locate " + iniPath);
        }
        /// <summary>
        /// Returns the value for the given section, key pair.
        /// </summary>
        /// <param name="sectionName">Section name.</param>
        /// <param name="settingName">Key name.</param>
        public String GetSetting(String sectionName, String settingName)
        {
            SectionPair sectionPair;
            sectionPair.Section = sectionName;
            //.ToUpper();
            sectionPair.Key = settingName;
            //.ToUpper();
            var str = ((String)keyPairs[sectionPair]);
            return str!=null&&str.StartsWith("\"")?str.Substring(1,str.Length-2):str;
        }
        /// <summary>
        /// Enumerates all lines for given section.
        /// </summary>
        /// <param name="sectionName">Section to enum.</param>
        public String[] EnumSection(String sectionName)
        {
            ArrayList tmpArray = new ArrayList();
            foreach (SectionPair pair in keyPairs.Keys)
            {
                if (pair.Section == sectionName)
                    //.ToUpper())
                    tmpArray.Add(pair.Key);
            }
            return (String[])tmpArray.ToArray(typeof(String));
        }
        /// <summary>
        /// Adds or replaces a setting to the table to be saved.
        /// </summary>
        /// <param name="sectionName">Section to add under.</param>
        /// <param name="settingName">Key name to add.</param>
        /// <param name="settingValue">Value of key.</param>
        public void AddSetting(String sectionName, String settingName, String settingValue)
        {
            SectionPair sectionPair;
            sectionPair.Section = sectionName;
            //.ToUpper();
            sectionPair.Key = settingName;
            //.ToUpper();
            if (keyPairs.ContainsKey(sectionPair))
                keyPairs.Remove(sectionPair);
            keyPairs.Add(sectionPair, settingValue);
        }
        /// <summary>
        /// Adds or replaces a setting to the table to be saved with a null value.
        /// </summary>
        /// <param name="sectionName">Section to add under.</param>
        /// <param name="settingName">Key name to add.</param>
        public void AddSetting(String sectionName, String settingName)
        {
            AddSetting(sectionName, settingName, null);
        }
        /// <summary>
        /// Remove a setting.
        /// </summary>
        /// <param name="sectionName">Section to add under.</param>
        /// <param name="settingName">Key name to add.</param>
        public void DeleteSetting(String sectionName, String settingName)
        {
            SectionPair sectionPair;
            sectionPair.Section = sectionName;//.ToUpper();
            sectionPair.Key = settingName;//.ToUpper();
            if (keyPairs.ContainsKey(sectionPair))
                keyPairs.Remove(sectionPair);
        }
        /// <summary>
        /// Save settings to new file.
        /// </summary>
        /// <param name="newFilePath">New file path.</param>
        public void SaveSettings(String newFilePath)
        {
            ArrayList sections = new ArrayList();
            String tmpValue = "";
            String strToSave = "";
            foreach (SectionPair sectionPair in keyPairs.Keys)
            {
                if (!sections.Contains(sectionPair.Section))
                    sections.Add(sectionPair.Section);
            }
            foreach (String section in sections)
            {
                strToSave += ("[" + section + "]\r\n");
                foreach (SectionPair sectionPair in keyPairs.Keys)
                {
                    if (sectionPair.Section == section)
                    {
                        tmpValue = (String)keyPairs[sectionPair];
                        if (tmpValue != null)
                            tmpValue = "=" + tmpValue;
                        strToSave += (sectionPair.Key + tmpValue + "\r\n");
                    }
                }
                strToSave += "\r\n";
            }
            try
            {
                FileStream fs=new FileStream(newFilePath, FileMode.Create);
                TextWriter tw = new StreamWriter(fs,Encoding.GetEncoding("GB2312"));
                tw.Write(strToSave);
                tw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Save settings back to ini file.
        /// </summary>
        public void SaveSettings()
        {
            SaveSettings(iniFilePath);
        }
    }
View Code

 

标签:keyPairs,String,Windows,读写,INI,sectionPair,strLine,null,Section
From: https://www.cnblogs.com/cyj0923/p/16876266.html

相关文章

  • Windows下安装搭建MQTT服务器
    服务器常用的有emqx,还有apacheapolle,这里用的是emqx服务端以及客户端可以使用MQTTnet(NuGet包)一、MQTT服务器(emqx)搭建1.下载服务器MQTTBroker从https://www.emqx.i......
  • C# 读写App.config配置文件的方法
    、配置文件概述:应用程序配置文件是标准的XML文件,XML标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序。配置......
  • windows电脑连接oracle显示无监听程序
    这里需要保证两个服务已经启动  关闭后   启动后   ......
  • Windows路径或者Linux路径映射成web路径进行访问代码
    packagecom.soft.mpms.zframe.config;importjava.io.File;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.c......
  • 封装的一些windows进程相关的库
    my_pro.h/************************************************ MY_PRO.H 文件注释 文件名:MY_PRO.H 作者:czl 创建时间:2021/3/3121:22*************************......
  • Python在Windows中安装
    Python在Windows中安装Python3适用于Windows,MacOS和大多数Linux操作系统。即使Python2目前可用于许多其他操作系统,有部分系统Python3还没有提供支持或者支持了但被它......
  • [Kyana]配置Windows下的git环境
    01|前排提示git真好用,配置真麻烦。附:Linux系统上的安装只需要一行命令就到第三步了。再附:GitHub服务更大更全但经常上不去需要手动修改hosts,Gitee在国内更快更稳定但只......
  • Caused by: java.lang.NoClassDefFoundError: net/minidev/asm/FieldFilter 报错的解
    Causedby:org.springframework.beans.factory.BeanCreationException:Errorcreatingbeanwithname'requestMappingHandlerAdapter'definedinclasspathresourc......
  • windows版数据库mysql的安装
    一、下载MySQLMysql官网下载地址:MySQL::DownloadMySQLInstaller(ArchivedVersions)1.选择要安装的版本,本篇文章选择的是5.7.31版本,点击Download下载 正在上传......
  • Houdini Sop (Attribute Create)深入理解
    最近初学Houdini,在看sop节点,我是按官方帮助文档的sop顺序看的,应该不具有学习的参考意义,正经学houdini的应该没我这么干的。昨天看到AttributeCreate节点,对于里边的类型D......