Getting connection string in C # service

I am using VS 2008.

I have a service that needs to be deployed. The service will not be used from a .NET client (such as a website or a Windows client). This requires a database connection.

First, I had a console application that called the service, and the connection string was set in the app.config of the console application. I want to move the connection string to the service. Therefore, in the web.config file that comes with the service, I add 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 start the service, this connectionString is null. How to get this value from web.config?

I even added the following, but it also does not work:

 <appSettings> <add key="REConnectionString" value="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"/> </appSettings> 

If I scroll through the list of connection strings, it continues to return the connection string from the calling application. Is it not possible to use the configuration file?

+4
source share
2 answers

I right-clicked on the project and added a type connection string setting. And then I get it as:

 MyProject.Properties.Settings.Default.MyConnectionString; 
0
source

I will try to do 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 the name of the configuration file.
This should be the name of the exe or dll of the configuration file itself. OpenExeConfiguration will open a file with the name "name_of_your_service.exe.config" as a configuration object

OpenExeConfiguration Details

Just found an interesting question here on SO

+1
source

Source: https://habr.com/ru/post/1400163/


All Articles