如何在 Visual Studio Code 中添加 App.Config? [英] How to add an App.Config in Visual Studio Code?

查看:24
本文介绍了如何在 Visual Studio Code 中添加 App.Config?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Visual Studio Code 中使用连接字符串配置 C# 程序?

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

这适用于在 Visual Studio Code 1.34.0 中使用 .Net Core SDK 2.2.203 版的 .Net Core 2.2

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

我已尝试将 App.Config 文件添加到项目中,但无法解决此问题.请告诉我任何配置连接字符串的解决方案.

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

推荐答案

安装 Microsoft.Extensions.Configuration.Json

Install Microsoft.Extensions.Configuration.Json

然后将 appsettings.json 文件添加到项目中并右键单击文件 -properties 并选择复制到输出为副本(如果更新)

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

示例 appsetting.json 文件

sample appsetting.json file

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

这篇关于如何在 Visual Studio Code 中添加 App.Config?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆