Can .NET load and parse a properties file equivalent to Java Properties class?

前端 未结 13 1679
死守一世寂寞
死守一世寂寞 2020-12-01 01:19

Is there an easy way in C# to read a properties file that has each property on a separate line followed by an equals sign and the value, such as the following:



        
13条回答
  •  半阙折子戏
    2020-12-01 01:45

    No there is not : But I have created one easy class to help :

    public class PropertiesUtility
    {
        private static Hashtable ht = new Hashtable();
        public void loadProperties(string path)
        {
            string[] lines = System.IO.File.ReadAllLines(path);
            bool readFlag = false;
            foreach (string line in lines)
            {
                string text = Regex.Replace(line, @"\s+", "");
                readFlag =  checkSyntax(text);
                if (readFlag)
                {
                    string[] splitText = text.Split('=');
                    ht.Add(splitText[0].ToLower(), splitText[1]);
                }
            }
        }
    
        private bool checkSyntax(string line)
        {
            if (String.IsNullOrEmpty(line) || line[0].Equals('['))
            {
                return false;
            }
    
            if (line.Contains("=") && !String.IsNullOrEmpty(line.Split('=')[0]) && !String.IsNullOrEmpty(line.Split('=')[1]))
            {
                return true;
            }
            else
            {
                throw new Exception("Can not Parse Properties file please verify the syntax");
            }
        }
    
        public string getProperty(string key)
        {
            if (ht.Contains(key))
            {
                return ht[key].ToString();
            }
            else
            {
                throw new Exception("Property:" + key + "Does not exist");
            }
    
        }
    }
    

    Hope this helps.

提交回复
热议问题