Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Windows Service - Read from ini or App.config file

I have one Windows Polling Service to send an automatic email each 10 minutes. I use Thread.Sleep(new TimeSpan(0, 10, 0)); to sleep the thread for 10 minutes, which is hard coded right now.

To avoid hard coding, I have tried App.config which was not successful. I want to move the hard coding to some .ini files. How can I read .ini file from C# Windows Service.

EDIT: I try the below code to read from my windows service. string pollingInterval = (string)new AppSettingsReader().GetValue("PollingInterval", typeof(string)); Gives the below error. Configuration system failed to initialize

like image 214
Rauf Avatar asked Dec 18 '22 05:12

Rauf


2 Answers

app.config is better solution than INI file.

Your app.config file look something like below:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
.......
  <appSettings>
    <add key="TimerInterval" value="10" />
  </appSettings>
.......
</configuration>

And you read it like:

int timerInterval = Convert.ToInt32(ConfigurationManager.AppSettings["TimerInterval"]);

You need to import namespace using System.Configuration; and add reference to System.Configuration dll.

like image 193
Amit Joshi Avatar answered Dec 24 '22 01:12

Amit Joshi


Using App.config is as simple as

string interval = ConfigurationManager.AppSettings["interval"];

TimeSpan t;
TimeSpan.TryParseExact(interval, @"h\:m\:s", CultureInfo.InvariantCulture, out t);

(Don't forget to add the reference System.Configuration assembly and using System.Configuration + System.Globalization)

Your App.config:

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="interval" value="00:10:00" />
    </appSettings>
</configuration>
like image 27
Filburt Avatar answered Dec 24 '22 00:12

Filburt