C# 创建 Windows 服务时如何使用 App.Config 文件中 appSettings 的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14627824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use the value of appSettings from App.Config file when creating a Windows Service
提问by GibboK
I am trying to create a Windows Server. I have some logic in C#
我正在尝试创建一个 Windows 服务器。我在 C# 中有一些逻辑
string urlToPing = ConfigurationSettings.AppSettings["UrlToPing"].ToString();
Stream data = client.OpenRead(urlToPing);
I need to read
我需要阅读
Here my App.Config
这是我的 App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="UrlToPing" value="http://mysite.com"/>
</appSettings>
</configuration>
I am new at Windows Services, my questions:
我是 Windows 服务的新手,我的问题是:
- When I publish to folder the Service or if I create a build I cannot
see the App.Config file
- Visual Studio warning on ConfigurationSettings.AppSettings as obsolete (what should I use instead?)
- 当我将服务发布到文件夹或创建构建时,我看不到 App.Config 文件
- ConfigurationSettings.AppSettings 上的 Visual Studio 警告已过时(我应该改用什么?)
采纳答案by GibboK
To my second question I found a solution:
对于我的第二个问题,我找到了一个解决方案:
Add a reference to System.Configuration to your code file.
using System.Configuration;
The setting may now be referenced correctly...
ConfigurationManager.AppSettings["UrlToPing"].ToString();
向您的代码文件添加对 System.Configuration 的引用。
using System.Configuration;
现在可以正确引用该设置...
ConfigurationManager.AppSettings["UrlToPing"].ToString();
回答by wacdany
To your first question, when you build a executable project (Windows Service, Console Application, etc) it will rename the app.config to "YourApplication".exe.config where "YourApplication" is the name of your Startup assembly. It will then copy the file to your output folder.
对于您的第一个问题,当您构建可执行项目(Windows 服务、控制台应用程序等)时,它会将 app.config 重命名为“YourApplication”.exe.config,其中“YourApplication”是启动程序集的名称。然后它将文件复制到您的输出文件夹。