简体   繁体   中英

c# connection string and concatenation app.config

I have the following connection string through which i connect to an Access database(.mdb) located in a sub-folder inside the root-folder of my application :

 OleDbConnection con = new OledbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory() + "Data\rctts.mdb;Jet OLEDB:Database Password=mypassword;")

My question is, how do i put the connection string in the app.config file? Generally, i use :

 <connectionStrings>
    <add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

The issue i am facing is that in my connection string, i am doing some concatenations and also using System.AppDomain.CurrentDomain.BaseDirectory() to set the Data Source ... How do i do the same concatenation in app.config ? Is it possible to do so ?

Although configuration APIs offer no facilities to manipulate connection strings for you, you could place connection string "template" into configuration, and do the rest of manipulation in your code using string.Format :

Config:

<connectionStrings>
    <add name="Test" connectionString="Data Source={0}Data\rctts.mdb;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

C# code:

string conStr = string.Format(
    ConfigurationManager.ConnectionStrings["Test"].ConnectionString
,   System.AppDomain.CurrentDomain.BaseDirectory()
);

You could try the following:

connectionString="Data Source=|DataDirectory|\rctts.mdb;Initial Catalog=OmidPayamak;Integrated Security=True"

and then try to set the value of DataDirectory as below:

var currentDomain = AppDomain.CurrentDomain;
var basePath = currentDomain.BaseDirectory;
currentDomain.SetData("DataDirectory", basePath+"\Data");

at the corresponding startup file of your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM