Save settings into xml file

sarthemaker

Active member
Joined
Sep 4, 2009
Messages
36
Programming Experience
5-10
I am working on a file explorer, and I want to save the view settings of each folder, like the icon size, font size, ect.. I was thinking of using an xml file to save these settings. But I am not sure how to do this? Could anyone help me out?
 
First up, please post in the most appropriate forum for the topic of the thread, not just the first one you come to. Thread moved.

As for the question, there are different ways you could go about it but I would suggest that the simplest would be to use serialisation. First you should define a type that has properties for all the values you want to persist. Saving is then a few lines and so is loading. You can even build that functionality into the type itself, e.g.
VB.NET:
Public Class MyCustomType

    Private _number As Integer
    Private _text As String

    Public Property Number() As Integer
        Get
            Return _number
        End Get
        Set(ByVal value As Integer)
            _number = value
        End Set
    End Property

    Public Property Text() As String
        Get
            Return _text
        End Get
        Set(ByVal value As String)
            _text = value
        End Set
    End Property

    Public Sub Save(ByVal path As String)
        Dim serialiser As New XmlSerializer(Me.GetType())

        Using file As New FileStream(path, FileMode.Create)
            serialiser.Serialize(file, Me)
        End Using
    End Sub

    Public Shared Function Load(ByVal path As String) As MyCustomType
        Dim deserialiser As New XmlSerializer(GetType(MyCustomType))

        Using file As New FileStream(path, FileMode.Open)
            Return DirectCast(deserialiser.Deserialize(file), MyCustomType)
        End Using
    End Function

End Class
VB.NET:
Dim obj1 As New MyCustomType With {.Number = 100, .Text = "Hello World"}
Dim filePath As String = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "MyCustomType.xml")

obj1.Save(filePath)

Dim obj2 As MyCustomType = MyCustomType.Load(filePath)

MessageBox.Show(obj2.Number.ToString(), obj2.Text)
 
Back
Top