C# Windows 服务 - 从 ini 或 App.config 文件中读取

Rau*_*auf 4 c# ini windows-services

我有一个 Windows 轮询服务每 10 分钟自动发送一封电子邮件。我曾经Thread.Sleep(new TimeSpan(0, 10, 0));让线程休眠 10 分钟,现在是硬编码的。

为了避免硬编码,我尝试过App.config没有成功。我想将硬编码移动到一些.ini文件中。如何.ini从 C# Windows 服务读取文件。

编辑:我尝试使用下面的代码从我的 Windows 服务中读取。 string pollingInterval = (string)new AppSettingsReader().GetValue("PollingInterval", typeof(string)); 给出以下错误。Configuration system failed to initialize

Ami*_*shi 7

app.config 是比 INI 文件更好的解决方案。

您的app.config文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
.......
  <appSettings>
    <add key="TimerInterval" value="10" />
  </appSettings>
.......
</configuration>
Run Code Online (Sandbox Code Playgroud)

你这样读:

int timerInterval = Convert.ToInt32(ConfigurationManager.AppSettings["TimerInterval"]);
Run Code Online (Sandbox Code Playgroud)

您需要导入命名空间using System.Configuration;并添加对 System.Configuration dll 的引用。


Fil*_*urt 5

使用 App.config 非常简单

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

TimeSpan t;
TimeSpan.TryParseExact(interval, @"h\:m\:s", CultureInfo.InvariantCulture, out t);
Run Code Online (Sandbox Code Playgroud)

(不要忘记添加参考System.Configuration程序集和using System.Configuration+ System.Globalization

您的应用程序配置:

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="interval" value="00:10:00" />
    </appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)