コード例 #1
0
        public static void Main(string[] args)
        {
            IniFileData iniFileData = Parser.ParseFile("/Users/anastasia/Desktop/ООП/lab3/lab3/Example.ini");

            Console.WriteLine(iniFileData["ADC_DEV"].GetFloat("BufferLenSeconds"));
            Console.WriteLine(iniFileData["NCMD"].GetInt("TidPacketVersionForTidControlCommand"));
            Console.WriteLine(iniFileData["ADC_DEV"].GetString("Driver"));
            try
            {
                Console.WriteLine(iniFileData["ADC_DEV"].GetString("fnjrkg")); //exception test
            }
            catch (KeyNotFound e)
            {
                Console.WriteLine("fnjrkg not found");
            }
        }
コード例 #2
0
        public static IniFileData ParseFile(string path)
        {
            IniFileData iniFileData = new IniFileData();

            string[] lines;

            if (!path.Substring(path.IndexOf('.') + 1, path.Length - path.IndexOf('.') - 1).Equals("ini"))
            {
                throw new FileFormatException();
            }


            try
            {
                lines = File.ReadAllLines(path);
            }
            catch (FileNotFoundException)
            {
                throw new FileNotFound();
            }
            catch (DirectoryNotFoundException)
            {
                throw new DirectoryNotFound();
            }

            string sectionName = null;

            foreach (var line in lines)
            {
                string str = line;
                str.Trim();
                str = DeleteComment(str);

                if (str.Length == 0)
                {
                    continue;
                }

                if (str[0].Equals('['))
                {
                    sectionName = str.Substring(1, str.IndexOf(']') - 1);
                    if (!IsValidNaming(sectionName))
                    {
                        throw new InvalidNamingException();
                    }
                    iniFileData.AddSection(sectionName);
                }
                else if (sectionName == null)
                {
                    throw new InvalidSyntaxException();
                }
                else
                {
                    string[] lineComponents = str.Split('=');
                    if (lineComponents.Length == 2)
                    {
                        string fieldName = lineComponents[0].Trim();
                        if (!IsValidNaming(fieldName))
                        {
                            throw new InvalidNamingException();
                        }
                        iniFileData[sectionName].AddField(fieldName, lineComponents[1].Trim());
                    }
                    else
                    {
                        throw new InvalidSyntaxException();
                    }
                }
            }

            return(iniFileData);
        }