App.Config Connection String

前提是你 提交于 2019-12-22 14:54:07

问题


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..


回答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"];




回答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.




回答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.



来源:https://stackoverflow.com/questions/14918912/app-config-connection-string

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