In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to read the configuration file in NetCore. I hope you will get something after reading this article. Let's discuss it together.
In the 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 the study of .net Core starts from learning the configuration file. 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 .net Core, due to the cross-platform relationship, most configuration files exist in the form of json [appsetting.json] and can be hot loaded. With some simple examples, this paper briefly describes how to read the configuration file [Json,xml,ini, environment variables, etc.] in .Net Core, which is only for learning and sharing. If there are any deficiencies, please correct them.
Knowledge points involved
In this example, the configuration file is mainly read under the .net Core development environment, and the knowledge points involved are as follows:
The operation interface configured by the application program in IConfiguration:.Net Core mainly provides the function of reading Json,xml,ini, environment variables, memory data and so on.
ConfigurationBuilder: the builder utility class used to build the application configuration interface.
Install the plug-in
In .net Core, to read configuration files, you need to rely on the following plug-in packages, which can be installed through Nuget. The details are as follows:
Note: the parsing of different files by Net Core can be installed separately according to the needs of the actual project in different plug-in libraries. Object-oriented design ideas are also reflected here [such as: opening and closing principle, single responsibility principle].
Read the 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 an instance of IConfiguration interface
In .net Core, reading the pairing file is operated through the IConfiguration interface, and the instantiated interface object is as follows:
IConfiguration configuration = new ConfigurationBuilder (). SetBasePath (Environment.CurrentDirectory) .AddJsonFile ("student.json"). Build (); 3. Read through the indexer
By default, the IConfiguration API provides an indexer that reads with Key and returns a string object, as shown below:
Var name = configuration ["Name"]; / / the indexer included in the IConfiguration interface, which only returns the string type. For example, the name var like0 = configuration ["Like:0"]; / / read the first element in the array, such as: the first hobby var like2 = configuration ["Like:2"]; / / read the third element in the array, such as: the third hobby var landLit = configuration ["Score:LandLit"]; / / get the attribute values of the word node, such as Chinese scores
Note: if the Json data is hierarchical, it is represented by a colon [:].
4. Read through the GetValue () method
The indexer can only return values of type string. If you need to read other simple types of objects, such as int,float, you can do so through the GetValue () method, as shown below:
Var age = configuration.GetValue ("Age"); / / get other data types, such as int, age 5. Read array
Through indexers and generic methods, you can read objects of simple types, and if you need to read complex objects [such as arrays, lists, etc.], you need to use binding, as shown below:
/ / get the entire array, such as: hobby var like = new List (); configuration.Bind ("Like", like); 6. Overall object binding
The above examples are all about reading local data from a Json file, so can you convert the whole file to an object? In this way, it will be very convenient and quick to manipulate the object directly. The details are as follows:
First, copy the contents of the entire Json file, and then click "Edit-> paste selectively-- > paste JSON as a Class" menu, as shown below:
The default generated class is named 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 read 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. Json sample screenshot
Read XML file
XML file is also a commonly used configuration file in application development. The read operation to the XML file is basically similar to the Json file operation, as shown below:
1. Create a XML file
First create a XML file, as follows:
Alan.hsiang 20 male basketball football swimming 90 98 60 2. Simple read
It can be read through the indexer and GetValue, as follows:
/ / 1. Basic read var age = configuration.GetValue ("Age"); / / get other data types, such as: int, such as age var name = configuration ["Name"]; / / the indexer included in the IConfiguration API, which only returns the string type. For example, the name var like0 = configuration ["Likes:Like:0"]; / / read the first element in the array, such as: the first hobby var like2 = configuration ["Likes:Like:2"]; / / read the third element in the array, such as: the third hobby var landLit = configuration ["Score:LandLit"]; / / get the attribute values of the word node, such as Chinese scores
Note: reading elements in an array is different from json reading, because there is one node in json, but three nodes in xml.
3. Read array
Read the array list in XML, as follows:
/ / get the entire array, such as: hobby var like= new List (); configuration.Bind ("Likes:Like", like); Console.WriteLine ($"name= {name}, age= {age}, like= {string.Join (", ", like)}"); 4. Bind objects as a whole
The above examples are all about reading local data from a XML file, so can you convert the whole file to an object? In this way, it will be very convenient and quick to manipulate the object directly. The details are as follows:
First, copy the contents of the entire XML file, and then click "Edit-> paste selectively-- > paste XML as a Class" menu, as shown below:
The default generated class has the same name as the root node of XML, as shown below:
Namespace DemoCore {/ / Note: the generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0. / / [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 / / public string Name {get {return this.nameField;} set {this.nameField = value }} / / public byte Age {get {return this.ageField;} set {this.ageField = value }} / / public string Sex {get {return this.sexField;} set {this.sexField = value }} / / [System.Xml.Serialization.XmlArrayItemAttribute ("Like", IsNullable = false)] public string [] Likes {get {return this.likesField;} set {this.likesField = value }} / / public StudentScore Score {get {return this.scoreField;} set {this.scoreField = value } / [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 / / public byte LandLit {get {return this.landLitField;} set {this.landLitField = value }} / / public byte Mathematics {get {return this.mathematicsField;} set {this.mathematicsField = value }} / / public byte English {get {return this.englishField;} set {this.englishField = value;}
However, the default generated class has a problem when converting to an array, so it needs to be adjusted slightly, as shown below:
Namespace DemoCore {/ / Note: the generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0. / / [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 / / public string Name {get {return this.nameField;} set {this.nameField = value }} / / public byte Age {get {return this.ageField;} set {this.ageField = value }} / / public string Sex {get {return this.sexField;} set {this.sexField = value }} / / [System.Xml.Serialization.XmlArrayItemAttribute ("Like", IsNullable = false)] public LikesLike Likes {get {return this.likesField;} set {this.likesField = value }} / / public StudentScore Score {get {return this.scoreField;} set {this.scoreField = value } / [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 / / public byte LandLit {get {return this.landLitField;} set {this.landLitField = value }} / / public byte Mathematics {get {return this.mathematicsField;} set {this.mathematicsField = value }} / / public byte English {get {return this.englishField;} set {this.englishField = value;}} public partial class LikesLike {public string [] Like {get; set }}}
Then, when reading, do the overall binding, as shown below:
/ / 2. Complex read 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. Sample screenshot
Note: there is a slight difference between reading the XML and reading the Json file in the sample direction.
Read INI file
Ini files are not widely used in C # programs, mainly key-value files, which are mainly used to store simple data formats, as shown below:
1. Create an ini file
Generally speaking, the ini file includes the following parts: a. The comments are prefixed with semicolons, b. Nodes are represented by square brackets, and c. Key=value represents content As follows:
Here is the comment [student] Name=Alan.hsiang Age=20 Grade=42. Create a configuration and read
The steps to read the ini file in .net Core are very simple, as follows:
Private static void ReadIni () {IConfiguration configuration = new ConfigurationBuilder () .SetBasePath (Environment.CurrentDirectory) .AddinitiFile ("student.ini") .Build (); string name = configuration ["student:Name"]; / / if there is no node, var age = configuration.GetValue ("student:Age"); var grade = configuration.GetValue ("student:Grade") Console.WriteLine ($"name= {name}, age= {age}, grade= {string.Join (", ", grade)}");}
Note: since the ini file does not involve complex data structures, it can be done directly through the indexer and GetValue.
3. Sample screenshot
An example screenshot of reading an ini file is as follows:
Read environment variables
Environment variables (environment variables) generally refer to some parameters used in the operating system to specify the operating environment, such as temporary folder location and system folder location. Environment variables are equivalent to some parameters set to the system or user application, and what they do is of course related to the specific environment variables.
1. View environment variabl
In the win10 operating system, this computer-- > right-click-- > Properties-- > Advanced system Settings-- > Environment variables-- > then open the Environment variables dialog box. As follows:
Environment variables are divided into user variables [current users] and system variables [all users], as follows:
two。 Simple read
Read the value of the 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 an in arr) {Console.WriteLine (a) } Console.WriteLine ($"temp= {temp}\ nos= {os}");} 3. Sample screenshot
The screenshot of the example of reading environment variables is as follows:
After reading this article, I believe you have some understanding of "how to read configuration files in .NetCore". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.