Add connectionstring in app.config

后端 未结 6 1851
Happy的楠姐
Happy的楠姐 2020-12-17 07:05

I have a class library in C# has has several classes and a app.config. I have put ConnectionString in app.config as follows:


    &l         


        
相关标签:
6条回答
  • 2020-12-17 07:40

    The connection string stuff needs to be in the main exe project's app.config or else you need to load it manually.

    0 讨论(0)
  • 2020-12-17 07:46

    If you are running Web project with Class library, add connection string to web.config inside the Web project

    If you are running Console/WinForm project with Class library, add connection string to app.config inside the Console/WinForm project

    modifying config in Library project will not work in your case.

    0 讨论(0)
  • 2020-12-17 07:48

    In windows forms applications always add reference to System.Configuration in References then in the code page add using System.Configuration then use the connection strings like this:

    string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
    
    0 讨论(0)
  • 2020-12-17 07:49

    From what I understand, you have a class library with a configuration file with a connection string and are referencing that library in another app. The problem is an app.config (or web.config) is relative to the executing application.

    Say your class library is named Shared.dll and have a Shared.dll.config and another application (let's say it's a Console Application) called Application with Application.exe.config. When running that application, the app.config used will be Application.exe.config.

    If you are trying trying to access a connection string named TRN_DB in this application, it will look in the application's configuration file where it is not defined and return null (hence the Reference Exception).

    0 讨论(0)
  • 2020-12-17 07:50

    As others have said, the library will use the config file for the executing application.

    I'd like to add one suggestion though. One option to consider, for (in my opinion) a bit of polish and a professional touch is creating a custom configuration section. That would allow you to group the settings for your library and not leave any confusion about which settings are used by your library: http://msdn.microsoft.com/en-us/library/2tw134k3(v=vs.100).aspx

    0 讨论(0)
  • 2020-12-17 07:56

    I had a similar problem and the issue turned out to be that I needed to add System.Configuration to the References.

    I thought adding using System.Configuration; to the class would do the trick but I had to add System.Configuration to the references before it would work.

    0 讨论(0)
提交回复
热议问题