Reputation: 26048
I'm using VS 2008.
I have a service that needs to be deployed. The service won't be used from a .NET client (like a website or Windows client). It needs a database connection.
I initially had a console app that called the service, and the connection string was set in the app.config of the console app. I want to move the connection string to the service. So in the web.config that come with the service I put in the following:
<connectionStrings>
<clear />
<add name="REConnectionString"
connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
And in my MyService.svc.cs I have the following:
private readonly string connectionString = ConfigurationManager.ConnectionStrings["REConnectionString"].ConnectionString;
But when I run the service this value connectionString is null. How do I get this value from the web.config?
I have even added the following but it is also not working:
<appSettings>
<add key="REConnectionString" value="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"/>
</appSettings>
If I loop through the list of connection string then it keeps on bring back the connection string from the calling app. Is there no way that the config file can be used?
Upvotes: 4
Views: 5851
Reputation: 26048
I right clicked on the project and added a setting of type connection string. And then I retrieve it like:
MyProject.Properties.Settings.Default.MyConnectionString;
Upvotes: 0
Reputation: 216333
I will try with something like this:
Configuration config = ConfigurationManager.OpenExeConfiguration("name_of_your_service.exe");
string connectString = config.ConnectionStrings["YourConnectionStringNameHere"];
You should pay attention to the string passed as name of the config file.
It should be the name of an exe or dll not the config file itself.
OpenExeConfiguration will open as Configuration object a file named "name_of_your_service.exe.config"
Details on OpenExeConfiguration
Just found an interesting question here on SO
Upvotes: 1