6

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.

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

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Rauf
  • 12,326
  • 20
  • 77
  • 126
  • Possible duplicate of [Reading/writing an INI file](https://stackoverflow.com/questions/217902/reading-writing-an-ini-file) – Romano Zumbé Jul 27 '17 at 08:42
  • 2
    "I have tried `App.config` which was not successful." - why and how was it "not successful"? That would usually be the preferred way to store information like that. Have you read https://stackoverflow.com/questions/13043530/what-is-app-config-in-c-net-how-to-use-it ? – Corak Jul 27 '17 at 08:47
  • 1
    What's the issue with using a App.config? Side note: Your task sounds like it could be simply solved by running a console application from Windows Task Scheduler rather than running an idling Windows Service. – Filburt Jul 27 '17 at 08:48

2 Answers2

11

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.

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
5

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>
Filburt
  • 17,626
  • 12
  • 64
  • 115