C# 在我的程序中保存和加载设置的最佳方法是什么?

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

What is the best way for save and load setting in my program?

c#application-settings

提问by Gold

I have build a C# program.

我已经构建了一个 C# 程序。

I need to keep setting of my program and I need to load them when the program load

我需要继续设置我的程序,我需要在程序加载时加载它们

(I know to do it with simple text file....but i don't have good documentation of the variable)

(我知道用简单的文本文件来做......但我没有很好的变量文档)

what is the best way to do it ?

最好的方法是什么?

Can I get any sample ?

我可以得到任何样品吗?

回答by Vinay Sajip

Use appSettings(that's the MSDN link, here's more of a quick overview).

使用appSettings(这是 MSDN 链接,这里有更多的快速概述)。

回答by kostia

How about storing the settings in XML?

如何将设置存储在 XML 中?

Reading and writing them is pretty easy.

阅读和编写它们非常容易

回答by jasonh

In your solution, if you right click on the project and click on properties, there's a settings tab. You can define the settings you want to track and their types there and then access them through code, like this:

在您的解决方案中,如果您右键单击项目并单击属性,则会出现一个设置选项卡。您可以在那里定义要跟踪的设置及其类型,然后通过代码访问它们,如下所示:

Properties.Settings.Default.SettingName = "Test Value";
Properties.Settings.Default.Save();

And then on load:

然后加载:

textBox.Text = Properties.Settings.Default.SettingName;

回答by Steffen Opel

I'd argue that just hinting towards appSettingsdoesn't really cover the topic, as there is more advanced and eventually easier to use stuff readily available. Given that this question might be a

我认为只是暗示appSettings并不能真正涵盖该主题,因为有更高级且最终更易于使用的现成工具。鉴于这个问题可能是一个

Duplicate

复制

Best way to save per user options in C#

在 C# 中保存每个用户选项的最佳方法

Please note that the MSDN link provided there (User settings in C#) covers both user and application scoped settings on an easy to grasp introductory level and basically elaborates on the correct example provided by jasonh already.

请注意,那里提供的 MSDN 链接(C# 中的用户设置)涵盖了用户和应用程序范围的设置,易于掌握的介绍级别,并且基本上详细说明了 jasonh 提供的正确示例。

For a much deeper coverage of these topics (assuming you are using Windows Forms or WPF with Visual Studio) I'd recommend to look into Application Settings for Windows Forms.

为了更深入地了解这些主题(假设您在 Visual Studio 中使用 Windows 窗体或 WPF),我建议您查看Windows 窗体的应用程序设置