【问题标题】:App.Config file in console application C#控制台应用程序 C# 中的 App.Config 文件
【发布时间】:2012-04-21 14:13:23
【问题描述】:


我有一个控制台应用程序,我想在其中写入文件名。

Process.Start("blah.bat");

通常,我会在 Windows 应用程序中通过将文件名 'blah.bat' 写入 Properties 中的 Settings 文件来获得类似的东西。
但是,在这里我没有找到任何 Settings 文件,我添加了一个 app.config 用于相同目的。

我不确定在 app.config 中写什么,这会导致我实现与 Windows 窗体中类似的事情.

例如:在 Windows 窗体中。 Process.Start(Properties.Settings.Default.BatchFile);
其中BatchFile 是属性设置文件中的字符串。

【问题讨论】:

    标签: c# console


    【解决方案1】:

    您可以在项目中添加对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>
    

    【讨论】:

    • ConfigurationSettings.AppSettings["blah.bat"] 可用,但会发出警告,指出它已过时。当我尝试如上所述使用ConfigurationManager 时,我收到一条错误消息,指出当前上下文中不存在 ConfigurationManager。 :-/
    • 确保您还添加了对 System.Configuration 的引用 - using 指令仅在您引用了您尝试使用的程序集时才有效。
    • 迟到的评论,但对我来说,我的错误是我忘记了 appSettings 中的大写“S”
    • 我如何获得 int 或 bool,即不是字符串?
    • @Zapnologica 一切都是字符串,只要考虑AppSettings。如果您有包含数字的设置字符串,则必须通过调用int.TryParse() 或类似方法来解析它们。对于您想要处理字符串以外的任何其他值也是如此。
    【解决方案2】:

    对于 .NET Core,从 NuGet 管理器添加 System.Configuration.ConfigurationManager。
    并从 App.config

    中读取 appSetting
    <appSettings>
      <add key="appSetting1" value="1000" />
    </appSettings>
    

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

    ConfigurationManager.AppSettings.Get("appSetting1")
    

    【讨论】:

      【解决方案3】:

      使用这个

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

      【讨论】:

      • 您可以将您的配置保存在 appsettion 和 Fetch 值使用示例中。
      • 提供对运行时版本 1.x 的支持。现在是obsolete。请使用System.Configuration.ConfigurationManager.AppSettings
      • 引用中需要 System.Configuration 程序集。
      猜你喜欢
      • 2022-11-11
      • 2013-10-27
      • 2010-09-14
      • 1970-01-01
      • 2015-08-14
      • 2011-11-28
      • 1970-01-01
      • 2019-08-27
      相关资源
      最近更新 更多