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

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

    Yeah there's no built in classes to do this that I'm aware of.

    But that shouldn't really be an issue should it? It looks easy enough to parse just by storing the result of Stream.ReadToEnd() in a string, splitting based on new lines and then splitting each record on the = character. What you'd be left with is a bunch of key value pairs which you can easily toss into a dictionary.

    Here's an example that might work for you:

    public static Dictionary GetProperties(string path)
    {
        string fileData = "";
        using (StreamReader sr = new StreamReader(path))
        {
            fileData = sr.ReadToEnd().Replace("\r", "");
        }
        Dictionary Properties = new Dictionary();
        string[] kvp;
        string[] records = fileData.Split("\n".ToCharArray());
        foreach (string record in records)
        {
            kvp = record.Split("=".ToCharArray());
            Properties.Add(kvp[0], kvp[1]);
        }
        return Properties;
    }
    

    Here's an example of how to use it:

    Dictionary Properties = GetProperties("data.txt");
    Console.WriteLine("Hello: " + Properties["Hello"]);
    Console.ReadKey();
    

提交回复
热议问题