Get ConnectionString from app.config in c# [duplicate]

痞子三分冷 提交于 2019-12-19 10:17:28

问题


I have defined my connection String in app.config file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>

    <add name="CString" 
         connectionString="Data Source=Bilal-PC;Initial Catalog=ATMSoftware;Integrated Security=False; User Id=sa; Password=123" 
         providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>

Now I want to get it into my C# class and I have tried all the methods. but I am getting an error on configuration manager.

Please help me.


回答1:


Ensure that you have added a reference to System.Configuration in your project, and place a

using System.Configuration;

statement at the top of your source. The ConfigurationManager type should now be available.

string connectionString = ConfigurationManager.ConnectionStrings["CString"].ConnectionString;



回答2:


See MSDN for more information

var conString = ConfigurationManager.ConnectionStrings["LocalSqlServer"];
string strConnString = conString.ConnectionString;


来源:https://stackoverflow.com/questions/8693492/get-connectionstring-from-app-config-in-c-sharp

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