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

use*_*679 89 c# console


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

Process.Start("blah.bat");
Run Code Online (Sandbox Code Playgroud)

通常情况下,我会通过写文件的名称在Windows应用程序类似的东西'blah.bat'设置文件属性.
但是,在这里我没有找到任何设置文件,我添加了一个app.config用于相同的目的.

我不知道在app.config中写什么,这将导致我实现与Windows窗体类似的东西.

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

xxb*_*bcc 186

您可以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>
Run Code Online (Sandbox Code Playgroud)

  • 确保您还添加了对System.Configuration的引用 - 只有当您引用要尝试使用的程序集时,`using` durective才有效. (67认同)
  • `ConfigurationSettings.AppSettings ["blah.bat"]`可用,但会发出警告,说明这已经过时了.当我尝试使用上面的`ConfigurationManager`时,我得到一个错误,说当前上下文中不存在ConfigurationManager.: - / (8认同)

Zin*_*Min 9

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

<appSettings>
  <add key="appSetting1" value="1000" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

从NuGet Manager添加System.Configuration.ConfigurationManager

在此处输入图片说明

ConfigurationManager.AppSettings.Get("appSetting1")
Run Code Online (Sandbox Code Playgroud)


小智 5

用这个

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")
Run Code Online (Sandbox Code Playgroud)

  • 提供对运行时版本 1.x 的支持。现在这是[已过时](https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationsettings.appsettings?redirectedfrom=MSDN&amp;view=netframework-4.7.2#System_Configuration_ConfigurationSettings_AppSettings)。请使用“System.Configuration.ConfigurationManager.AppSettings” (3认同)