簡介 保存應用程序設置是一項常見任務。過去,我們通常將設置保存到 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