Reputation: 1916
In my windows form i have connection string in app.config as
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Database"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
And in all classes i am using the following code to connect to the database.
string connString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
But its not connected to the database.
Can somebody point out the mistake.
But when i use this code without use of app.config it works fine.
string connString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source = C:\\Users\\Amrit\\Desktop\\Database.accdb; Persist Security Info = False;";
How can i make the app.config connection string work..
Upvotes: 2
Views: 20514
Reputation: 583
you need to set DataDirectory.
You can then set the path in Application_Start in your Global.ascx.cs
AppDomain.CurrentDomain.SetData("DataDirectory", "C:\Users\Amrit\Desktop");
https://stackoverflow.com/a/1409378/2745294
https://stackoverflow.com/a/6708279/2745294
Hope this helps.
Upvotes: 0
Reputation: 18443
It seams (from the comments) that you are targeting two difference database files in those two connection strings. The first one is in your App_Data
folder of your project, and the second one resides on your desktop.
The file in your App_Data
folder is copied in to the output folder (bin/Debug
or bin/Release
for a WinForms project) every time you start the project in the VS. It overwrites previous contents of the file so every time you have a fresh copy of the file form the App_Data
folder in your output folder. To find out, run the program and execute a few insertions. Then close the program and open the database file in the output folder (not in projects App_Data
).
This happens because you have set the Copy to Output Directory
property of the database file to Copy always
.
Upvotes: 0
Reputation: 1384
You may do it so
<configuration>
<appSettings>
<add key="ApplicationTitle" value="Sample Console Application" />
<add key="ConnectionString"
value="Server=localhost;Database=Northwind;Integrated
Security=false;User Id=sa;Password=;" />
</appSettings>
then use ConfigurationSettings.AppSettings["ConnectionString"];
Upvotes: 0