在 Windows 窗体 C# 应用程序中拥有配置文件的最简单方法 [英] Simplest way to have a configuration file in a Windows Forms C# application

查看:24
本文介绍了在 Windows 窗体 C# 应用程序中拥有配置文件的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

1<MyCustomPath>C:SomePathHere</MyCustomPath>

有没有简单的方法来做到这一点?能否简单解释一下如何读写一个简单的配置文件?

解决方案

您想使用 App.Config.

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

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

喜欢:

<预><代码><配置><应用设置><add key="MyKey" value="false"/>

通过执行访问成员

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

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

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

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

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

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.

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

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

<MyCustomValue>1</MyCustomValue>
<MyCustomPath>C:SomePathHere</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?

解决方案

You want to use an 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.

这篇关于在 Windows 窗体 C# 应用程序中拥有配置文件的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆