如何在 Windows 窗体应用程序中保存应用程序设置? [英] How can I save application settings in a Windows Forms application?

查看:61
本文介绍了如何在 Windows 窗体应用程序中保存应用程序设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要实现的目标非常简单:我有一个使用路径读取信息的 Windows 窗体 (.NET 3.5) 应用程序.用户可以使用我提供的选项表单修改此路径.

What I want to achieve is very simple: I have a Windows Forms (.NET 3.5) application that uses a path for reading information. This path can be modified by the user, by using the options form I provide.

现在,我想将路径值保存到文件中以备后用.这将是保存到此文件的众多设置之一.此文件将直接位于应用程序文件夹中.

Now, I want to save the path value to a file for later use. This would be one of the many settings saved to this file. This file would sit directly in the application folder.

我知道有三个选项可用:

I understand three options are available:

  • 配置设置文件(appname.exe.config)
  • 注册表
  • 自定义 XML 文件

我读到 .NET 配置文件无法将值保存回它.至于注册表,我想尽可能远离它.

I read that the .NET configuration file is not foreseen for saving values back to it. As for the registry, I would like to get as far away from it as possible.

这是否意味着我应该使用自定义 XML 文件来保存配置设置?

Does this mean that I should use a custom XML file to save configuration settings?

如果是这样,我想看看它的代码示例(C#).

If so, I would like to see code example of that (C#).

我看过其他关于这个主题的讨论,但我仍然不清楚.

I have seen other discussions on this subject, but it is still not clear to me.

推荐答案

如果您使用 Visual Studio,那么很容易获得可持久化的设置.右键单击解决方案资源管理器中的项目并选择属性.选择设置"选项卡,如果设置不存在,请单击超链接.

If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.

使用设置"选项卡创建应用程序设置.Visual Studio 创建文件 Settings.settingsSettings.Designer.settings,其中包含从 ApplicationSettingsBase.你可以从你的代码访问这个类来读/写应用程序设置:

Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings and Settings.Designer.settings that contain the singleton class Settings inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:

Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file

此技术适用于控制台、Windows 窗体和其他项目类型.

This technique is applicable both for console, Windows Forms, and other project types.

请注意,您需要设置设置的 scope 属性.如果您选择应用程序范围,则 Settings.Default. 将是只读的.

Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.

参考:如何:使用 C# 在运行时编写用户设置 - Microsoft Docs

Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs

这篇关于如何在 Windows 窗体应用程序中保存应用程序设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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