如何在Visual Studio Code中添加App.Config?

3
如何在Visual Studio Code中配置一个带有连接字符串的C#程序?
这是针对使用.Net Core SDK版本2.2.203的.Net Core 2.2,在Visual Studio Code 1.34.0中进行的。
我尝试将App.Config文件添加到项目中,但我无法解决这个问题。请告诉我任何配置连接字符串的解决方案。
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);
        }
    }
}
2个回答

4

安装Microsoft.Extensions.Configuration.Json

然后将appsettings.json文件添加到项目中,右键单击该文件 -属性,并选择复制到输出目录作为如果较新则复制

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);

示例 appsetting.json 文件

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

1
您的代码中使用了ConfigurationManager.ConnectionStrings来获取连接字符串。然而,在.NET Core 2.2及以上版本中,这段代码将无法工作,因为ConfigurationManager.ConnectionStrings用于获取ASP.NET项目的web.config和控制台/Winforms/WPF项目的app.config中的连接字符串,只有当您的应用程序使用.NET Framework时才能使用。
在.NET Core 2.0及更高版本中,大多数配置都存储为JSON文件,默认情况下,相当于web.config/app.config的文件是appsettings.json文件,您也可以拥有自己的配置文件,因为它非常易于扩展。
关于如何管理配置文件的官方.NET Core 2.0(或更高版本)文档可在此链接找到:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-2.2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接