How to add an App.Config in Visual Studio Code?

余生颓废 提交于 2021-01-27 12:29:39

问题


How to configure a C# program with a connection string in Visual Studio Code?

This is for .Net Core 2.2 using .Net Core SDK version 2.2.203 in Visual Studio Code 1.34.0

I have tried to add App.Config file to the project, but I'm not able to resolve this issue. Do let me know any solution to configure connection string.

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;  
using System.Web;
using System.Configuration;
using System.Collections.Specialized;
using Dapper;

namespace Sample_Dapper
{
    class Program
    {
        static void Main(string[] args)
        {
            IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);

            var SqlString = "SELECT TOP 100 [CustomerID],[CustomerFirstName], 
                             [CustomerLastName],[IsActive] FROM [Customer]";
            var ourCustomers = (List<Customer>)db.Query<Customer>(SqlString);
        }
    }
}

回答1:


Install Microsoft.Extensions.Configuration.Json

Then add appsettings.json file to project and right click on file -properties and select copy to output as copy if newer

var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        IConfigurationRoot configuration = builder.Build();

        Console.WriteLine(configuration.GetConnectionString("Test"));

        Console.WriteLine(configuration.GetSection("SampleObj:AnyPropName").Value);

sample appsetting.json file

 {
  "SampleObj": {
    "AnyPropName" :  "testProp" 
  } ,
  "ConnectionStrings": {
    "Test": "CONNECTION-STRING"
  }
}



回答2:


Your code has ConfigurationManager.ConnectionStrings to get the connection string. This code will not work in .NET Core 2.2 and later, because ConfigurationManager.ConnectionStrings is used to get connection strings in web.config for ASP.NET project and app.config for console and Winforms/WPF projects if your app is using .NET Framework.

In .NET Core 2.0 and later, most configuration is stored as JSON file, and by default the equivalent of web.config/app.config is appsettings.json file, and you can also have your own configuration file as well, because it is highly extensible.

The official .NET Core 2.0 (or later) documentation on how to manage configuration files is available at: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2



来源:https://stackoverflow.com/questions/56256722/how-to-add-an-app-config-in-visual-studio-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!