quinta-feira, 7 de julho de 2016

C# Ini Parser

Como C# (C sharp) não tem parser para arquivo.ini por seus motivos, corretos ou não, disponibilizo uma função simples para mapear valores ini em Coleções(Collection) de dicionários(Dictionary),

        public Dictionary<string, Dictionary<string, string>> readConfig(string filePath)
        {
            // Se não tem arquivo, retorna
            if (!File.Exists(filePath)) { return null; }

            Dictionary<string, Dictionary<string, string>> config;
            config = new Dictionary < string, Dictionary < string, string>>();

            string line;
            string session="_"; // sessão não nomeada, sem sessão ou comum
            StreamReader iniFile = new StreamReader(filePath);

            while ( (line = iniFile.ReadLine()) != null )
            {
                int p;
                // Remove comentários da linha
                if ((p = line.IndexOf('#')) >= 0) line = line.Substring(0, p);
                if ((p = line.IndexOf(';')) >= 0) line = line.Substring(0, p);
                // Verifica se é valor e pega posição do =
                if ((p = line.IndexOf('=')) >= 0)
                { // valor ou variavel
                    string key = line.Substring(0, p).Trim();
                    string value = line.Substring(p + 1).Trim();
                    if (config.ContainsKey(session))
                    {
                        config[session].Add( key, value );
                    }
                    else
                    {
                        config.Add(session, new Dictionary<string, string>() { { key, value } });
                    }
                } else if ( (p = line.IndexOf('[')) >= 0)  // inicio de sessão
                {
                    session = line.Substring(p + 1) ;
                    if ( (p=session.IndexOf(']')) >= 0 )
                    {
                        session = session.Substring(0, p);
                    }
                }
            }
            return config;
        }