Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Read a specific configuration file in ASP.Net Application

$
0
0

I have a .net class library that makes a connection to a SQL server database and performs CRUD operations.

The library is called by a windows forms project as well as a WCF service project.

For the purpose of this discussion, lets call the library DataAccess.

In a typical .net environment, I would have stored the connection string in the app.config of the windows forms project and also in the web.config of the WCF service project. In fact, this is what I originally had and the code worked fine.

The customer requested that the connection string be stored in the app.config of the DataAccess library which becomes DataAccessLibrary.dll.config.

The place where I read connection string is in one place in the DataAccessLibrary. I have my post build scripts defined to copy the DataAccessLibrary.dll.config to the output directory of both the web application as well as the windows forms application.

The windows forms application works fine but the web application does not work.

Here is the code:

If (HttpContext.Current Is Nothing) Then 'not a web application
            config = ConfigurationManager.OpenExeConfiguration(ExecutingAssemblyPath)

            'ExecutingAssemblyPath is initialized to Me.GetType.Assembly.GetName.Name + ".dll"

            'so its value is DataAccess.dll.config

Else 'called from an application other than web service
            config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~")
End If

ConnectionString = config.ConnectionStrings.ConnectionStrings("MyConnectionName").ConnectionString

When I execute the WCF service, the 'else' part of the code does not work because it reads from the web.config. So I tried to change the path to:

config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(ExecutingAssemblyPath)

and I got the error:

The relative virtual path 'DataAccess.dll' is not allowed here.

So I changed the code to:

WebConfigurationManager.OpenWebConfiguration("~/" + ExecutingAssemblyPath)

A configuration was loaded this time but when I see the value of connection strings, it seems like its loading machine.config or some other config file.

Is there a way to load a specific configuration file this way in a web application? I can do this in a windows forms application and so I am hoping it can be done in a web application.


Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>