1
我需要將創建的對象保存到Windows註冊表中,並在重新打開應用程序後才能讀取它?我知道如何保存和讀取字符串,但這是複雜的對象。使用VB.NET將用戶定義的對象保存到Windows註冊表中
有什麼想法?
我需要將創建的對象保存到Windows註冊表中,並在重新打開應用程序後才能讀取它?我知道如何保存和讀取字符串,但這是複雜的對象。使用VB.NET將用戶定義的對象保存到Windows註冊表中
有什麼想法?
您可能想要使用XmlSerializer(或其他序列化程序)。它很容易使用,並且文檔中充滿了示例。
但爲什麼將它存儲在註冊表中?
更好地使用Application Settings and User Settings。
編輯:
取而代之的是註冊表的,你的對象保存在用戶的的ApplicationData目錄中的文件。你可以得到路徑與此目錄
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
完整的示例:
Imports System.IO
Imports System.Xml.Serialization
Module Module1
Public Class MySuperClass
Public Property MyString() As String
Public Property MyInt() As Int32
End Class
Public Sub Main(ByVal args() As String)
Dim myFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MyApplication")
If Not Directory.Exists(myFolder) Then
Directory.CreateDirectory(myFolder)
End If
Dim myFile = Path.Combine(myFolder, "MySettings.txt")
Dim o = New MySuperClass With {.MyString = "Hi!", .MyInt = 42}
Dim x = New XmlSerializer(GetType(MySuperClass))
Using sr = New StreamWriter(myFile)
' Save directly to file
x.Serialize(sr, o)
End Using
' for demonstrating purpose
o = Nothing
Using sr = New StreamReader(myFile)
' Load directly from file
o = CType(x.Deserialize(sr), MySuperClass)
End Using
End Sub
End Module
同意。將複雜的對象存儲在註冊表中並不是一個好主意。最好將其存儲爲用戶配置文件中的文件。 –
謝謝!我重新打開apllications後需要該對象。除了保存在註冊表中還有其他方法嗎? – Nenad
@Nenad查看我的完整示例的更新答案 – sloth