How to Read and Write Configuration Files in the .NET Core Console Application

Asked 2 years ago, Updated 2 years ago, 47 views

How do I read and write configuration files in the .NET Core console application?
The .NET Framework had the necessary feature in the namespace System.configuration, but it does not appear to exist in .NET Core.

ASP.NET Core seems to have something convenient to read and write configuration files, but do I have to implement it myself for regular console applications?

I don't know what to give in the builder.Add(""); section below.
All you want to do is read and write the values in key values from the configuration file.

using System;
    using System.Collections.General;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.Memory;
    using Microsoft.Extensions.Options;

    namespace ConsoleApp1
    {
        public class program
        {

            public static void Main (string[]args)
            {
                Console.WriteLine("");

                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.Add("");

                varconfig = builder.Build();
                config ["somekey" = "somevalue";
                string setting2 = config ["somekey" ];
            }
        }
    }

c# .net

2022-09-30 17:18

1 Answers

This is a self-answer, but I was able to do the following.
I'll give you an answer.

using System;
    using System.Collections.General;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Configuration.Memory;
    using Microsoft.Extensions.Options;

    namespace ConsoleApp1
    {
        public class program
        {

            public static void Main (string[]args)
            {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.AddXmlFile(@"setting.xml", optional:true);
                builder.AddEnvironmentVariables();

                try
                {
                    varconfig = builder.Build();
                    config ["somekey" = "somevalue";
                    string setting2 = config ["somekey" ];

                    Console.WriteLine(setting2);

                }catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);

                }
            }
        }
    }


2022-09-30 17:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.