'App.Config Connection String
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..
Solution 1:[1]
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"];
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dotmido |
| Solution 2 | |
| Solution 3 | Community |
