.net 在 Windows 窗体 C# 应用程序中拥有配置文件的最简单方法

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

Simplest way to have a configuration file in a Windows Forms C# application

.netxmlwinformsconfiguration

提问by Fabio Gomes

I'm really new to .NET, and I still didn't get the hang about how configuration files work.

我对 .NET 真的很陌生,但我仍然不了解配置文件的工作原理。

Every time I search on Google about it I get results about web.config, but I'm writing a Windows Forms application.

每次我在 Google 上搜索它时,我都会得到有关 web.config 的结果,但我正在编写一个 Windows 窗体应用程序。

I figured out that I need to use the System.Configuration namespace, but the documentation isn't helping.

我发现我需要使用 System.Configuration 命名空间,但文档没有帮助。

How do I define that my configuration file is XYZ.xml? Or does it have a "default" name for the configuration file? I still didn't get that.

我如何定义我的配置文件是 XYZ.xml?或者它有配置文件的“默认”名称吗?我还是没明白。

Also, how do I define a new section? Do I really need to create a class which inherits from ConfigurationSection?

另外,我如何定义一个新部分?我真的需要创建一个继承自 ConfigurationSection 的类吗?

I would like to just have a configuration file with some values like this:

我只想拥有一个包含以下值的配置文件:

<MyCustomValue>1</MyCustomValue>
<MyCustomPath>C:\Some\Path\Here</MyCustomPath>

Is there a simple way to do it? Can you explain in a simple way how to read and write from/to a simple configuration file?

有没有简单的方法来做到这一点?你能用简单的方式解释一下如何从/向一个简单的配置文件读取和写入吗?

回答by qui

You want to use an App.Config.

您想使用 App.Config。

When you add a new item to a project there is something called Applications Configuration file. Add that.

当您向项目添加新项目时,会出现称为应用程序配置文件的内容。添加那个。

Then you add keys in the configuration/appsettings section

然后在配置/应用设置部分添加密钥

Like:

喜欢:

<configuration>
 <appSettings>
  <add key="MyKey" value="false"/>

Access the members by doing

通过执行访问成员

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

This works in .NET 2 and above.

这适用于 .NET 2 及更高版本。

回答by ZombieSheep

Clarification of previous answers...

澄清以前的答案...

  1. Add a new file to your project (AddNew ItemApplication Configuration File)

  2. The new configuration file will appear in Solution Explorer as App.Config.

  3. Add your settings into this file using the following as a template

    <configuration>
      <appSettings>
        <add key="setting1" value="key"/>
      </appSettings>
      <connectionStrings>
        <add name="prod" connectionString="YourConnectionString"/>
      </connectionStrings>
    </configuration>
    
  4. Retrieve them like this:

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }
    
  5. When built, your output folder will contain a file called <assemblyname>.exe.config. This will be a copy of the App.Configfile. No further work should need to be done by the developer to create this file.

  1. 向您的项目添加一个新文件(添加新项目应用程序配置文件

  2. 新的配置文件将作为App.Config出现在解决方案资源管理器中。

  3. 使用以下作为模板将您的设置添加到此文件中

    <configuration>
      <appSettings>
        <add key="setting1" value="key"/>
      </appSettings>
      <connectionStrings>
        <add name="prod" connectionString="YourConnectionString"/>
      </connectionStrings>
    </configuration>
    
  4. 像这样检索它们:

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }
    
  5. 构建后,您的输出文件夹将包含一个名为 <assemblyname>.exe.config 的文件。这将是App.Config文件的副本。开发人员无需为创建此文件而做进一步的工作。

回答by maxfurni

From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses app.config(copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click Settings.settingsin your project's "Properties" folder.

快速阅读之前的答案,它们看起来是正确的,但似乎没有人提到 Visual Studio 2008 中的新配置工具。它仍然使用app.config(在编译时复制到 YourAppName.exe.config),但是有一个 UI 小部件来设置属性并指定它们的类型。双击项目“属性”文件夹中的Settings.settings

The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in app.configwould be accessed like:

最好的部分是从代码访问这个属性是类型安全的——编译器会发现明显的错误,比如输入错误的属性名称。例如,可以像这样访问app.config 中名为 MyConnectionString 的属性:

string s = Properties.Settings.Default.MyConnectionString;

回答by Nathan Koop

You should create an App.configfile (very similar to web.config).

您应该创建一个App.config文件(非常类似于web.config)。

You should right click on your project, add new item, and choose new "Application Configuration File".

您应该右键单击您的项目,添加新项目,然后选择新的“应用程序配置文件”

Ensure that you add using System.Configuration in your project.

确保在项目中使用 System.Configuration 添加。

Then you can add values to it:

然后你可以给它添加值:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="setting1" value="key"/>
  </appSettings>
  <connectionStrings>
    <add name="prod" connectionString="YourConnectionString"/>
  </connectionStrings>
</configuration>


    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }


Just a note: According to Microsoft, you should use ConfigurationManager instead of ConfigurationSettings (see the remarks section):

请注意:根据 Microsoft,您应该使用 ConfigurationManager 而不是 ConfigurationSettings (请参阅备注部分):

"The ConfigurationSettings class provides backward compatibility only. For new applications you should use the ConfigurationManager class or WebConfigurationManager class instead. "

“ConfigurationSettings 类仅提供向后兼容性。对于新应用程序,您应该改用 ConfigurationManager 类或 WebConfigurationManager 类。”

回答by Mike Dimmick

The default name for a configuration file is [yourexe].exe.config. So notepad.exe will have a configuration file named notepad.exe.config, in the same folder as the program. This is a general configuration file for all aspects of the CLR and Framework, but it can contain your own settings under an <appSettings>node.

配置文件的默认名称是 [yourexe].exe.config。所以notepad.exe会有一个名为notepad.exe.config的配置文件,在程序所在的文件夹中。这是 CLR 和框架所有方面的通用配置文件,但它可以在<appSettings>节点下包含您自己的设置。

The <appSettings>element creates a collection of name-value pairs which can be accessed as System.Configuration.ConfigurationSettings.AppSettings. There is no way to save changes back to the configuration file, however.

<appSettings>元素创建了一个名称-值对的集合,可以作为 访问System.Configuration.ConfigurationSettings.AppSettings。但是,无法将更改保存回配置文件。

It is also possible to add your own custom elements to a configuration file - for example, to define a structured setting - by creating a class that implements IConfigurationSectionHandlerand adding it to the <configSections>element of the configuration file. You can then access it by calling ConfigurationSettings.GetConfig.

也可以将您自己的自定义元素添加到配置文件中 - 例如,定义结构化设置 - 通过创建一个实现类IConfigurationSectionHandler并将其添加到<configSections>配置文件的元素中。然后您可以通过调用访问它ConfigurationSettings.GetConfig

.NET 2.0 adds a new class, System.Configuration.ConfigurationManager, which supports multiple files, with per-user overrides of per-system data. It also supports saving modified configurations back to settings files.

.NET 2.0 添加了一个新类 ,System.Configuration.ConfigurationManager它支持多个文件,每个用户覆盖每个系统数据。它还支持将修改后的配置保存回设置文件。

Visual Studio creates a file called App.config, which it copies to the EXE folder, with the correct name, when the project is built.

Visual Studio 会创建一个名为 的文件App.config,在生成项目时,它会使用正确的名称将其复制到 EXE 文件夹中。

回答by TcKs

The best (IMHO) article about .NET Application configuration is on CodeProject, Unraveling the Mysteries of .NET 2.0 Configuration. And my next favorite (shorter) article about sections in the .NET configuration files is Understanding Section Handlers - App.config File.

关于 .NET 应用程序配置的最佳 (恕我直言) 文章是关于 CodeProject, Unraveling the Mysteries of .NET 2.0 Configuration。我最喜欢的(较短的)关于 .NET 配置文件中的部分的文章是了解部分处理程序 - App.config 文件

回答by configurator

In Windows Forms, you have the app.configfile, which is very similar to the web.configfile. But since what I see you need it for are custom values, I suggest using Settings.

在 Windows 窗体中,您拥有与app.config文件非常相似的web.config文件。但由于我认为您需要的是自定义值,因此我建议使用Settings

To do that, open your project properties, and then go to settings. If a settings file does not exist you will have a link to create one. Then, you can add the settings to the table you see there, which would generate both the appropriate XML, and a Settingsclass that can be used to load and save the settings.

为此,请打开您的项目属性,然后转到设置。如果设置文件不存在,您将有一个创建一个的链接。然后,您可以将设置添加到您在那里看到的表中,这将生成适当的 XML 和可用于加载和保存设置的Settings类。

The settings class will be named something like DefaultNamespace.Properties.Settings. Then, you can use code similar to:

设置类将命名为类似DefaultNamespace.Properties.Settings. 然后,您可以使用类似于以下内容的代码:

using DefaultNamespace.Properties;

namespace DefaultNamespace {
    class Class {
        public int LoadMySettingValue() {
            return Settings.Default.MySettingValue;
        }
        public void SaveMySettingValue(int value) {
            Settings.Default.MySettingValue = value;
        }
    }
}

回答by Jamie Ide

I agree with the other answers that point you to app.config. However, rather than reading values directly from app.config, you should create a utility class (AppSettings is the name I use) to read them and expose them as properties. The AppSettings class can be used to aggregate settings from several stores, such as values from app.config and application version info from the assembly (AssemblyVersion and AssemblyFileVersion).

我同意将您指向 app.config 的其他答案。但是,与其直接从 app.config 读取值,不如创建一个实用程序类(AppSettings 是我使用的名称)来读取它们并将它们作为属性公开。AppSettings 类可用于聚合来自多个存储区的设置,例如来自 app.config 的值和来自程序集(AssemblyVersion 和 AssemblyFileVersion)的应用程序版本信息。

回答by Protagonist

A very simple way of doing this is to use your your own custom Settingsclass.

一个非常简单的方法是使用您自己的自定义Settings

回答by Protagonist

Use:

用:

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

AppSettings has been deprecated and is now considered obsolete (link).

AppSettings 已被弃用,现在被认为已过时(链接)。

In addition, the appSettings section of the app.confighas been replaced by the applicationSettingssection.

此外,app.config的 appSettings 部分已被applicationSettings部分取代。

As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.

正如其他人提到的,您应该使用 System.Configuration.ConfigurationManager(链接),这是 .NET 2.0 的新功能。