The .net core console application reads the configuration file app.config

read app.config

  1. Create a new console project
    My development environment here is win7 + vs2019 + .net core 3.1

  2. Add app.config, add a file to select the application configuration file, the default file name will be App.config, click Add.
    insert image description here

  3. An app.config file in xml format will be generated here, the content is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
  1. We add configuration information to it, for example:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<appSettings>
		<add key="username" value="admin" />
		<add key="token" value="d2232" />
		<add key="sqlconnection" value="sqlserver" />
		<add key="hehe" value="haha" />
	</appSettings>
</configuration>
  1. New NuGet package
    insert image description here
  2. Write code, read configuration.
using System;
using System.Configuration;

namespace ConfigTest
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    

            //单个读取
            var hehe = ConfigurationManager.AppSettings["hehe"];

            Console.WriteLine(hehe);

            //遍历
            foreach (string key in ConfigurationManager.AppSettings.AllKeys)
            {
    
    
                Console.WriteLine(ConfigurationManager.AppSettings[key]);
            }
        }
    }
}

If it is .net framwork, you don't need nuget, just add the reference directly,
insert image description here

Guess you like

Origin blog.csdn.net/mrtwenty/article/details/126621159