在C#控制台应用程序中的App.Config文件

120
我有一个控制台应用程序,我想在其中写入一个文件的名称。
Process.Start("blah.bat");

通常,在Windows应用程序中,我会通过将文件名'blah.bat'写入设置文件并保存到属性中实现此功能。
但是,在这里我没有找到任何设置文件,因此我添加了一个app.config以达到同样的目的。

我不确定在app.config中要写什么,才能像Windows Forms那样实现类似的功能。

例如:在Windows Forms中,使用Process.Start(Properties.Settings.Default.BatchFile);
其中BatchFile是保存在属性中的设置文件中的字符串。

3个回答

274
你可以在项目中添加对System.Configuration的引用,然后: using System.Configuration; 然后使用如下语句: string sValue = ConfigurationManager.AppSettings["BatchFile"]; 需要一个像这样的app.config文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
       <add key="BatchFile" value="blah.bat" />
   </appSettings>
</configuration>

14
ConfigurationSettings.AppSettings["blah.bat"] 可用,但会发出警告表示此方法已经过时。当我尝试使用 ConfigurationManager 时,却收到了“当前上下文中不存在 ConfigurationManager”的错误提示。:-/ - user1240679
73
请确保还添加了对System.Configuration的引用 - 当你尝试使用一个程序集时,只有添加了引用才能使用“using”指令。 - xxbbcc
1
晚了点评论,但对我来说我的错误是我忘记了将appSettings中的'S'大写。 - user10864482
如何获取 int 或 bool 类型的变量,而不是字符串? - Zapnologica
1
@Zapnologica 就 AppSettings 而言,所有东西都是字符串。如果您有包含数字的设置字符串,则必须通过调用 int.TryParse() 或类似方法来解析它们。对于任何其他您想要将其视为字符串以外的值,也是如此。 - xxbbcc

50

对于.NET Core,请从NuGet管理器中添加System.Configuration.ConfigurationManager。
然后从App.config中读取appSetting

<appSettings>
  <add key="appSetting1" value="1000" />
</appSettings>

从 NuGet 管理器中添加 System.Configuration.ConfigurationManager。

输入图片说明

ConfigurationManager.AppSettings.Get("appSetting1")

7

使用这个

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

1
你可以将配置保存在“appsettion”中,对于获取值,请使用示例。 - user5705992
3
提供对运行时版本1.x的支持。这已经过时了。请使用System.Configuration.ConfigurationManager.AppSettings - wp78de
1
需要在引用中添加 System.Configuration 程序集。 - Muflix

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接