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
Adding and reading from a Config file
提问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. 在那个项目中,我有一些变量companyName,companyType例如字符串。
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.
我需要创建一个配置文件,并从中读取值,然后初始化变量companyName,companyType在代码中。
- How can i create a config file (or equivalent) ?
- How can i read from the config file ?
- 如何创建配置文件(或等效文件)?
- 我如何从配置文件中读取?
采纳答案by goric
Add an
Application Configuration Fileitem to your project (Right -ClickProject > Add item). This will create a file calledapp.configin your project.Edit the file by adding entries like
<add key="keyname" value="someValue" />within the<appSettings>tag.Add a reference to the
System.Configurationdll, and reference the items in the config using code likeConfigurationManager.AppSettings["keyname"].
Application Configuration File向您的项目中添加一个项目(Right -Click项目 > 添加项目)。这将创建一个app.config在您的项目中调用的文件。通过
<add key="keyname" value="someValue" />在<appSettings>标签内添加条目来编辑文件。添加对
System.Configurationdll的引用,并使用类似ConfigurationManager.AppSettings["keyname"].
回答by Oded
Right click on the project file -> Add -> New Item -> Application Configuration File. This will add an
app.config(orweb.config) file to your project.The
ConfigurationManagerclass would be a good start. You can use it to read different configuration values from the configuration file.
右键单击项目文件 -> 添加 -> 新建项目 -> 应用程序配置文件。这将向您的项目添加一个
app.config(或web.config)文件。这
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);

