Reading/writing an INI file

后端 未结 16 2393
南旧
南旧 2020-11-22 00:15

Is there any class in the .NET framework that can read/write standard .ini files:

[Section]
=
...

Delphi has th

16条回答
  •  遇见更好的自我
    2020-11-22 00:55

    I found this simple implementation:

    http://bytes.com/topic/net/insights/797169-reading-parsing-ini-file-c

    Works well for what I need.

    Here is how you use it:

    public class TestParser
    {
        public static void Main()
        {
            IniParser parser = new IniParser(@"C:\test.ini");
    
            String newMessage;
    
            newMessage = parser.GetSetting("appsettings", "msgpart1");
            newMessage += parser.GetSetting("appsettings", "msgpart2");
            newMessage += parser.GetSetting("punctuation", "ex");
    
            //Returns "Hello World!"
            Console.WriteLine(newMessage);
            Console.ReadLine();
        }
    }
    

    Here is the code:

    using System;
    using System.IO;
    using System.Collections;
    
    public class IniParser
    {
        private Hashtable keyPairs = new Hashtable();
        private String iniFilePath;
    
        private struct SectionPair
        {
            public String Section;
            public String Key;
        }
    
        /// 
        /// Opens the INI file at the given path and enumerates the values in the IniParser.
        /// 
        /// Full path to INI file.
        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);
    
                    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);
    
        }
    
        /// 
        /// Returns the value for the given section, key pair.
        /// 
        /// Section name.
        /// Key name.
        public String GetSetting(String sectionName, String settingName)
        {
            SectionPair sectionPair;
            sectionPair.Section = sectionName.ToUpper();
            sectionPair.Key = settingName.ToUpper();
    
            return (String)keyPairs[sectionPair];
        }
    
        /// 
        /// Enumerates all lines for given section.
        /// 
        /// Section to enum.
        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));
        }
    
        /// 
        /// Adds or replaces a setting to the table to be saved.
        /// 
        /// Section to add under.
        /// Key name to add.
        /// Value of key.
        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);
        }
    
        /// 
        /// Adds or replaces a setting to the table to be saved with a null value.
        /// 
        /// Section to add under.
        /// Key name to add.
        public void AddSetting(String sectionName, String settingName)
        {
            AddSetting(sectionName, settingName, null);
        }
    
        /// 
        /// Remove a setting.
        /// 
        /// Section to add under.
        /// Key name to add.
        public void DeleteSetting(String sectionName, String settingName)
        {
            SectionPair sectionPair;
            sectionPair.Section = sectionName.ToUpper();
            sectionPair.Key = settingName.ToUpper();
    
            if (keyPairs.ContainsKey(sectionPair))
                keyPairs.Remove(sectionPair);
        }
    
        /// 
        /// Save settings to new file.
        /// 
        /// New file path.
        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
            {
                TextWriter tw = new StreamWriter(newFilePath);
                tw.Write(strToSave);
                tw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    
        /// 
        /// Save settings back to ini file.
        /// 
        public void SaveSettings()
        {
            SaveSettings(iniFilePath);
        }
    }
    

提交回复
热议问题