简介 保存应用程序设置是一项常见任务。过去,我们通常将设置保存到 INI 文件或注册表中。而在 Microsoft® .NET 框架中,我们多了另一种选择,即将应用程序设置序列化到 xml 文件中,以便轻松地更新和检索这些设置。Microsoft Visual Studio® .NET 使用 System.Configuration.AppSettingsReader 类读取存储在配置文件中的 DynamicPRoperties。但是,这些动态属性在运行时是只读的,因此您无法保留用户所做的更改。本文将介绍如何序列化数据并将其写入一个文件,以及如何读取和反序列化该数据。存储数据的方式和位置取决于要存储的内容,本文将讨论如何根据数据类型将其存储到相应的位置。
保存应用程序设置的前提 Windows 窗体 application 类包含多个属性,答应您轻松导航到注册表或用户数据文件夹的相应部分。要正确使用这些属性,您必须设置 AssemblyCompany、AssemblyProdUCt 和 AssemblyVersion 属性。
这些属性设置的值由 Control 类通过 CompanyName、ProductName 和 ProductVersion 属性公开。
下面是一个简单的 Windows 窗体示例,其中设置了程序集属性并将其显示在 Label 中:
' Visual Basic Imports System Imports System.Windows.Forms Imports System.Reflection
' 设置程序集属性。
Public Class AboutDialogBox Inherits Form
Public Sub New() ' 在 Label 中显示程序集信息。 Dim label1 As New Label() label1.Text = _ Me.CompanyName + " " + _ Me.ProductName + " 版本: " + _ Me.ProductVersion label1.AutoSize = True Me.Controls.Add(label1) End Sub End Class
//C# using System; using System.Windows.Forms; using System.Reflection;
// 设置程序集属性。 [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("MyApplication")] [assembly: AssemblyVersion("1.0.1")] public class AboutDialogBox : Form { public AboutDialogBox() { // 在 Label 中显示程序集信息。 Label label1 = new Label(); label1.Text = this.CompanyName + " " + this.ProductName + " 版本: " + this.ProductVersion; label1.AutoSize = true; this.Controls.Add(label1); }
使用注册表存储数据 假如数据对应用程序而言非常敏感或十分重要,您可能不希望只简单地序列化数据;因为假如这样,任何人都可以使用文本编辑器查看或编辑这些数据;而注册表可以限制对数据的访问。注册表为应用程序和用户设置提供了强大的存储能力。多数备份程序会自动备份注册表设置。当您将信息放到注册表中的正确位置后,在存储设置时可自动避开用户。虽然用户可以编辑注册表,但他们通常不会这样做,这便使得您的设置更加稳定。总之,只要遵守使用注册表的 Microsoft Windows® 徽标原则,注册表将是存储应用程序设置的理想位置。
' Visual Basic Private appSettingsChanged As Boolean Private connectionString As String
Private Sub Form1_Closing(sender As Object, e As CancelEventArgs) Handles MyBase.Closing If appSettingsChanged Then Try ' 假如连接字符串已更改,则将其保存到注册表中。 Application.UserAppDataRegistry.SetValue("ConnString", _ connectionString) Catch ex As Exception MessageBox.Show(ex.Message ) End Try End If End Sub
' Visual Basic Private appSettingsChanged As Boolean Private connectionString As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Try ' 从注册表中获取连接字符串。 If Not (Application.UserAppDataRegistry.GetValue("ConnString") _ Is Nothing) Then connectionString = _ Application.UserAppDataRegistry.GetValue( _ "ConnString").ToString() statusBar1.Text = "连接字符串: " + connectionString End If Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub