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

前端 未结 13 1629
死守一世寂寞
死守一世寂寞 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 02:04

    I've written a method that allows emty lines, outcommenting and quoting within the file.

    Examples:

    var1="value1"
    var2='value2'

    'var3=outcommented
    ;var4=outcommented, too

    Here's the method:

    public static IDictionary ReadDictionaryFile(string fileName)
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        foreach (string line in File.ReadAllLines(fileName))
        {
            if ((!string.IsNullOrEmpty(line)) &&
                (!line.StartsWith(";")) &&
                (!line.StartsWith("#")) &&
                (!line.StartsWith("'")) &&
                (line.Contains('=')))
            {
                int index = line.IndexOf('=');
                string key = line.Substring(0, index).Trim();
                string value = line.Substring(index + 1).Trim();
    
                if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                    (value.StartsWith("'") && value.EndsWith("'")))
                {
                    value = value.Substring(1, value.Length - 2);
                }
                dictionary.Add(key, value);
            }
        }
    
        return dictionary;
    }
    
    0 讨论(0)
提交回复
热议问题