【问题标题】:Using .xml with Windows Service c#使用 .xml 和 Windows 服务 c#
【发布时间】:2013-03-08 13:00:55
【问题描述】:

我需要为我的服务使用 XML 来读取运行后可能会更改的值,而且我只能找到有关他们当前 XML 设置有问题的人的资源,而对于初学者来说几乎一无所获。

谁能简要解释一下在设计 Windows 服务时如何开始使用 XML,或者向我指出一个初学者可以理解的好资源的方向?

谢谢

【问题讨论】:

  • 在 Windows 服务中尝试使用 Xml 时,您遇到了哪些具体困难?
  • Xml 不讨厌 Windows 服务,也不偏爱其他类型的项目。发布您想用 Xml 做什么以及您面临的具体问题。
  • 你有 app.config 用于输入值吗?
  • 我创建的服务将 MSGID 和 CONTENT 从 .eml 文件中取出,然后使用给定参数创建另一个 .eml 文件 - 这些参数必须不时更改,但服务必须保持运行。
  • 我也不知道如何使用 App config

标签: c# xml windows-services


【解决方案1】:

xml与windows服务无关。

在 c# 中有多种使用方法,一种简单的方法是 XmlDocument 类。

例如

XmlDocument configDoc = new XmlDocument();
configDoc.Load("ServiceConfig.xml");
XmlNode pollingNode = configDoc.DocumentElement.SelectSingleNode("PollingInterval");
if (pollingNode != null)
{
/// Grab pollingNode.InnerText, convert to an int and set Property...
}

以上假设 xml 是

<Config>
<PollingInterval>30</PollingInterval>
</Config>

你最大的问题是你要把文件放在哪里,处理它被损坏,一些半智者将你锁定在它之外,它被删除......

在考虑这个想法之前我会先考虑一下。

【讨论】:

  • 我还能如何改变服务在运行时的运行方式?
  • @BenAshton 他们有理由在运行时这样做吗?许多应用程序要求您更改 app.config 文件,然后重新启动服务以使更改生效。如果您愿意,有很多方法可以在运行时更改它。您可以提供一个 GUI 作为单独的可执行文件,通过 WPF 与服务进行通信。
  • @JohnKoerner 似乎已经回答了这一点。文件很简单,甚至可能是作为原型的良好开端,但是通过接口实现它,然后你可以使用一些你不必处理它丢失/损坏或部分编辑的恐怖恐怖的东西。
  • 我已经和需要它的人谈过了,显然服务可以重新启动,你知道这个 app.config 东西的任何来源吗?谢谢!
  • 对你的问题的最后评论我发布了一个关于 C# Services 和 app.config 的问题的链接
【解决方案2】:

如果您愿意,可以使用 XML 序列化。这假定输出目录中有一个名为 Demo.xml 的文件:

string filePath = ".\\Demo.xml";
private void Form1_Load(object sender, EventArgs e)
{
    ReadSettings();
}

void ReadSettings()
{
    XmlSerializer s = new XmlSerializer(typeof(Settings));
    Settings newSettings = null;
    using (StreamReader sr = new StreamReader(filePath))
    {
        try
        {
            newSettings = (Settings)s.Deserialize(sr);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error:" + ex.ToString());
        }
    }
    if (newSettings != null)
        this.Text = newSettings.WatchPath;

}

public class Settings
{
    public string WatchPath { get; set; }
}

XML 格式:

<?xml version="1.0" encoding="utf-8" ?>
<Settings>
  <WatchPath>C:\Temp</WatchPath>
</Settings>

【讨论】:

  • 我明白了,我的意思是更多关于我能做什么 - 例如,我可以更改 xml 中变量的值吗?我该怎么做?
猜你喜欢
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多