C# 添加和读取配置文件

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

Adding and reading from a Config file

c#configuration-files

提问by Illep

I have created a C# console based project. In that project i have some variables like companyName, companyTypewhich are Strings.

我创建了一个C# console based project. 在那个项目中,我有一些变量companyNamecompanyType例如字符串。

companyName="someCompanyName";
companyType="someCompanyType";

I need to create a config file and read values from it, and then initialize the variables companyName, companyTypein the code.

我需要创建一个配置文件,并从中读取值,然后初始化变量companyNamecompanyType在代码中。

  1. How can i create a config file (or equivalent) ?
  2. How can i read from the config file ?
  1. 如何创建配置文件(或等效文件)?
  2. 我如何从配置文件中读取?

采纳答案by goric

  1. Add an Application Configuration Fileitem to your project (Right -ClickProject > Add item). This will create a file called app.configin your project.

  2. Edit the file by adding entries like <add key="keyname" value="someValue" />within the <appSettings>tag.

  3. Add a reference to the System.Configurationdll, and reference the items in the config using code like ConfigurationManager.AppSettings["keyname"].

  1. Application Configuration File向您的项目中添加一个项目(Right -Click项目 > 添加项目)。这将创建一个app.config在您的项目中调用的文件。

  2. 通过<add key="keyname" value="someValue" /><appSettings>标签内添加条目来编辑文件。

  3. 添加对System.Configurationdll的引用,并使用类似ConfigurationManager.AppSettings["keyname"].

回答by Oded

  1. Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an app.config(or web.config) file to your project.

  2. The ConfigurationManagerclass would be a good start. You can use it to read different configuration values from the configuration file.

  1. 右键单击项目文件 -> 添加 -> 新建项目 -> 应用程序配置文件。这将向您的项目添加一个app.config(或web.config)文件。

  2. ConfigurationManager门课将是一个好的开始。您可以使用它从配置文件中读取不同的配置值。

I suggest you start reading the MSDN document about Configuration Files.

我建议您开始阅读有关Configuration Files的 MSDN 文档。

回答by Matija Grcic

Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
KeyValueConfigurationCollection confCollection = configManager.AppSettings.Settings;

confCollection["YourKey"].Value = "YourNewKey";


configManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configManager.AppSettings.SectionInformation.Name);