Read configuration file of. Net Core foundation

In application development, the configuration file is the initial configuration information of the main storage system. Although the reading of the configuration file belongs to the basic content, it is often used, so a hundred feet high building rises from the ground and learns Net Core, start with the learning configuration file. Yes In the era of. net framework, the configuration file is mainly in xml format [web.config, app.config], and it needs to be restarted every time it is modified, but in In Net Core, due to the cross platform relationship, configuration files mostly exist in the form of JSON [appsetting.json], and can be hot loaded. With some simple examples, this paper briefly describes how to Net Core reads the configuration files [JSON, xml, ini, environment variables, etc.] for learning and sharing only. If there are deficiencies, please correct them.

Knowledge points involved

In this case, the main process is The knowledge points involved in reading configuration files in the Net Core development environment are as follows:

  •  IConfiguration: . The operation interface of application configuration in Net Core mainly provides the reading function of Json, xml, ini, environment variables, memory data, etc.
  • ConfigurationBuilder: the builder tool class used to build the application configuration interface.

Install plug-ins

Yes Net Core, in order to read the configuration file, you need to rely on the following plug-in packages, which can be installed through Nuget. The details are as follows:

Note: Net Core parses different files in different plug-in libraries, which can be installed separately according to the actual project needs. This also reflects the object-oriented design idea [such as opening and closing principle, single responsibility principle].

Read Json file

1. Prepare data

First prepare a Json file as follows:

{
  "Name": "Alan.hsiang",
  "Age": 20,
  "Sex": "male",
  "Like": ["basketball","football","swimming"],
  "Score": {
    "LandLit": 90,
    "Mathematics": 99,
    "English": 50
  }
}

2. Create IConfiguration interface instance

Yes Net Core, reading the pairing file is operated through IConfiguration interface, and the instantiated interface object is as follows:

IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("student.json").Build();

3. Read through indexer

By default, the IConfiguration interface provides an indexer to read with Key as the parameter and return string objects, as shown below:

var name = configuration["Name"]; //The indexer of IConfiguration interface only returns string type. For example: name
var like0 = configuration["Like:0"];//Read the first element in the array, such as the first element
var like2 = configuration["Like:2"];//Read the third element in the array, such as the third element
var landLit = configuration["Score:LandLit"];//Get the attribute value of byte point, such as Chinese score

Note: if Jason data has hierarchical relationship, it is represented by colon [:].

4. Read through getValue < T > ()

Only string type values can be returned through the indexer. If you need to read other simple types of objects, such as int,float, etc., you can use the getValue < T > () method, as shown below:

var age = configuration.GetValue<int>("Age");//Get other data types, such as int, such as age

5. Read array

Through indexers and generic methods, you can read simple types of objects. If you need to read complex objects [such as arrays, lists, etc.), you need to use binding, as shown below:

//Get the whole array, such as hobbies
var like = new List<string>();
configuration.Bind("Like",like);

6. Overall object binding

The above examples are all local data reading of the Json file. Can the entire file be converted into an object? In this way, it will be very convenient and fast to operate the object directly. The details are as follows:

First copy the contents of the entire JSON file, and then click the [edit -- > Paste Special -- > Paste JSON as class] menu successively, as shown below:

The default generated class name is RootObject, and then modified to Student, as shown below:

namespace DemoCore
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
        public string[] Like { get; set; }
        public Score Score { get; set; }
    }

    public class Score
    {
        public int LandLit { get; set; }
        public int Mathematics { get; set; }
        public int English { get; set; }
    }

}

Bind the Student class to the configuration object as follows:

//2. Complex reading
var student = new Student();
configuration.Bind(student);
Console.WriteLine($"name={student.Name},age={student.Age},like= {string.Join(",", student.Like)},score={student.Score.English}");

7. Screenshot of Jason example

Read XML file

XML file is also a commonly used configuration file in application development. The reading operation of XML file is basically similar to that of Json file, as shown below:

1. Create XML file

First create an XML file as follows:

<?xml version="1.0" encoding="utf-8" ?>
<Student>
    <Name>Alan.hsiang</Name>
    <Age>20</Age>
    <Sex>male</Sex>
    <Likes>
        <Like>basketball</Like>
        <Like>football</Like>
        <Like>swimming</Like>
    </Likes>
    <Score>
        <LandLit>90</LandLit>
        <Mathematics>98</Mathematics>
        <English>60</English>
    </Score>
</Student>

2. Simple reading

It can be read through indexer and GetValue, as shown below:

//1. Basic reading

var age = configuration.GetValue<int>("Age");//Get other data types, such as int, such as age
var name = configuration["Name"]; //The indexer of IConfiguration interface only returns string type. For example: name
var like0 = configuration["Likes:Like:0"];//Read the first element in the array, such as the first element
var like2 = configuration["Likes:Like:2"];//Read the third element in the array, such as the third element
var landLit = configuration["Score:LandLit"];//Get the attribute value of byte point, such as Chinese score

Note: when reading the elements in the array, it is different from json reading, because there is one node in json, but there are three nodes in xml.

3. Read array

Read the array list in XML as follows:

//Get the whole array, such as hobbies
var like = new List<string>();
configuration.Bind("Likes:Like", like);
Console.WriteLine($"name={name},age={age},like= {string.Join(",", like)}");

4. Overall binding object

The above examples are all local data reading of XML files. Can the whole file be converted into an object? In this way, it will be very convenient and fast to operate the object directly. The details are as follows:

First copy the contents of the entire XML file, and then click Edit -- > Paste Special -- > Paste XML as class menu successively, as shown below:

The default generated class, whose name is consistent with the root node of XML, is as follows:

namespace DemoCore
{
    // Note: the generated code may require at least NET Framework 4.5 or NET Core/Standard 2.0. 
    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Student
    {

        private string nameField;

        private byte ageField;

        private string sexField;

        private string[] likesField;

        private StudentScore scoreField;

        /// <remarks/>
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        public byte Age
        {
            get
            {
                return this.ageField;
            }
            set
            {
                this.ageField = value;
            }
        }

        /// <remarks/>
        public string Sex
        {
            get
            {
                return this.sexField;
            }
            set
            {
                this.sexField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("Like", IsNullable = false)]
        public string[] Likes
        {
            get
            {
                return this.likesField;
            }
            set
            {
                this.likesField = value;
            }
        }

        /// <remarks/>
        public StudentScore Score
        {
            get
            {
                return this.scoreField;
            }
            set
            {
                this.scoreField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class StudentScore
    {

        private byte landLitField;

        private byte mathematicsField;

        private byte englishField;

        /// <remarks/>
        public byte LandLit
        {
            get
            {
                return this.landLitField;
            }
            set
            {
                this.landLitField = value;
            }
        }

        /// <remarks/>
        public byte Mathematics
        {
            get
            {
                return this.mathematicsField;
            }
            set
            {
                this.mathematicsField = value;
            }
        }

        /// <remarks/>
        public byte English
        {
            get
            {
                return this.englishField;
            }
            set
            {
                this.englishField = value;
            }
        }
    }


}

However, there are problems in converting the default generated class into an array, so it needs to be slightly adjusted, as shown below:

namespace DemoCore
{
    // Note: the generated code may require at least NET Framework 4.5 or NET Core/Standard 2.0. 
    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
    public partial class Student
    {

        private string nameField;

        private byte ageField;

        private string sexField;

        private LikesLike likesField;

        private StudentScore scoreField;

        /// <remarks/>
        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        public byte Age
        {
            get
            {
                return this.ageField;
            }
            set
            {
                this.ageField = value;
            }
        }

        /// <remarks/>
        public string Sex
        {
            get
            {
                return this.sexField;
            }
            set
            {
                this.sexField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlArrayItemAttribute("Like", IsNullable = false)]
        public LikesLike Likes
        {
            get
            {
                return this.likesField;
            }
            set
            {
                this.likesField = value;
            }
        }

        /// <remarks/>
        public StudentScore Score
        {
            get
            {
                return this.scoreField;
            }
            set
            {
                this.scoreField = value;
            }
        }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class StudentScore
    {

        private byte landLitField;

        private byte mathematicsField;

        private byte englishField;

        /// <remarks/>
        public byte LandLit
        {
            get
            {
                return this.landLitField;
            }
            set
            {
                this.landLitField = value;
            }
        }

        /// <remarks/>
        public byte Mathematics
        {
            get
            {
                return this.mathematicsField;
            }
            set
            {
                this.mathematicsField = value;
            }
        }

        /// <remarks/>
        public byte English
        {
            get
            {
                return this.englishField;
            }
            set
            {
                this.englishField = value;
            }
        }
    }

    public partial class LikesLike {
        public string[] Like { get; set; }
    }
}

Then, when reading, bind as a whole, as shown below:

//2. Complex reading
var student = new Student();
configuration.Bind(student);
Console.WriteLine($"name={student.Name},age={student.Age},like= {string.Join(",", student.Likes.Like)},score={student.Score.English}");

5. Example screenshot

Note: there is a slight difference between reading XML and reading Json files through the example direction.

INI file read

ini files are not widely used in C# programs. They are mainly key value pair files, which are mainly used to store simple data formats, as shown below:

1. Create ini file

Generally, the ini file includes the following parts: a. comments are prefixed with semicolons, b. nodes are represented by brackets, and c. key=value represents content. As follows:

;Note here 
[student]
Name=Alan.hsiang
Age=20
Grade=4

2. Create configuration and read

Yes The steps of reading ini files in Net Core are very simple, as follows:

private static void ReadIni() {
    IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddIniFile("student.ini").Build();
    string name = configuration["student:Name"];//If there is no node, you can directly use the key to obtain it
    var age = configuration.GetValue<int>("student:Age");
    var grade = configuration.GetValue<int>("student:Grade");
    Console.WriteLine($"name={name},age={age},grade= {string.Join(",", grade)}");
 }

Note: since the ini file does not involve complex data structures, you can directly use the indexer and GetValue.

3. Example screenshot

An example screenshot of reading ini file is as follows:

Read environment variables

Environment variables generally refer to some parameters used in the operating system to specify the operating system running environment, such as temporary folder location and system folder location. Environment variables are equivalent to some parameters set for the system or user application. The specific function is certainly related to the specific environment variables.

1. View environment variables

In the win10 operating system, the computer -- > right-click -- > properties -- > advanced system settings -- > environment variables -- > and then open the environment variables dialog box. As follows:

Environment variables are divided into user variable [current user] and system variable [all users], as shown below:

2. Simple reading

Yes Read the value of environment variable in NetCore as follows:

private static void ReadEnvironmentVariable() {
      IConfiguration configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddEnvironmentVariables().Build();
       var path = configuration["Path"];
       var temp = configuration["TEMP"];
       var os = configuration["OS"];
       var arr = path.Split(";");
       Console.WriteLine("path:");
       foreach (var a in arr)
       {
           Console.WriteLine(a);
       }
       Console.WriteLine($"temp={temp}\n os= {os}");
}

3. Example screenshot

An example screenshot of reading environment variables is as follows:

remarks

The above is in Net Core is a way to read several common data in order to attract jade, learn together and make progress together.

Qianqiu years old · shushenghu [author] Zhang Xian [Dynasty] Song Dynasty

Count the sound. And report to Fangfei for a rest. Cherish the spring and fold the residual red. The rain is light, the wind is violent, and the plum is green. Yongfeng willow, no one flies flowers and snow all day.

Don't pull the single string. I can say it. It's hard to love until the day is old. The heart is like a double silk screen with thousands of knots in it. After the night, the east window is not white and the setting moon is not white.

Keywords: JSON xml .NET microsoft

Added by waqasahmed996 on Sat, 05 Mar 2022 16:28:39 +0200