C# 从 app.config 文件中读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10868428/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:36:07  来源:igfitidea点击:

Reading from a app.config file

c#app-config

提问by Illep

I am trying to print to Console.Writethe value of the key namefrom the following app.configfile.

我正在尝试从以下文件打印到Console.Write密钥的值。 nameapp.config

 <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="name" value="Chan" />
      </appSettings>
    </configuration>

C# code :

C# 代码:

Console.Write(ConfigurationManager.AppSettings["name"]);

Nothing gets printed in the console. Why is this ?

控制台中没有打印任何内容。为什么是这样 ?

Note: I have added a reference to the System.Configurationdll

注意:我添加了对System.Configurationdll的引用

采纳答案by Damith

below code gives you the content of active config file.

下面的代码为您提供了活动配置文件的内容。

var content  = File.ReadAllLines(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

Check what you get as content, is it contain key="name" value="Chan"or something else ?

检查你得到的content,是包含 key="name" value="Chan"还是别的什么?

if you given <add key="name" value="Chan" />then ConfigurationManager.AppSettings["name"] should return as Chan

如果你给出 <add key="name" value="Chan" />那么 ConfigurationManager.AppSettings["name"] 应该返回为Chan

回答by vpv

Given that your XML file (app.config) is properly formatted, try below.
Declare a variable and assign the variable the AppSettings value. Similar like-

鉴于您的 XML 文件 (app.config)格式正确,请尝试以下操作。
声明一个变量并将 AppSettings 值分配给该变量。类似的喜欢——

string sName = "";
sName = ConfigurationManager.AppSettings["name"].ToString();