Write and read data from XML file through VB.Net at launch

前端 未结 1 914
情深已故
情深已故 2021-01-26 09:08

I started doing some applications in VB.Net in the past year and a half and despite all my research for an answer, nothing has worked fine enough for me, so here I am, asking my

相关标签:
1条回答
  • 2021-01-26 10:00

    Use XML Serialization. IMO this is superior to using XDocuments in most cases. You will have an object with children which represent your xml file contents. You can iterate of the children, and everything is strongly-typed.

    Start by creating VB.NET classes to represent your data

    Option Strict On
    
    Imports System.IO
    Imports System.Xml.Serialization
    
    <XmlRoot("savedData")>
    Public Class SavedData
        <XmlElement("savedPassword")>
        Public Property SavedPasswords As List(Of SavedPassword)
    End Class
    
    Public Class SavedPassword
        <XmlAttribute("id")>
        Public Property ID As Byte
        <XmlElement("name")>
        Public Property Name As String
        <XmlElement("email")>
        Public Property Email As String
        <XmlElement("password")>
        Public Property Password As String
    End Class
    

    Once you have that, reading the file into your classes is pretty simple. Use the following code

    Dim filename = "filename.xml"
    Dim data As SavedData
    Dim serializer As New XmlSerializer(GetType(SavedData))
    Using sr = New StreamReader(filename)
        data = CType(serializer.Deserialize(sr), SavedData)
    End Using
    For Each sp In data.SavedPasswords
        Console.WriteLine($"id: '{sp.ID}', name: '{sp.Name}', email: '{sp.Email}', password: '{sp.Password}'")
    Next
    

    The only thing you need to do is to set the correct filename instead of Dim filename = "filename.xml". If the path is fixed, you can simply hard-code it

    Dim filename = "C:\VelocityDK Codes\Password Manager\filename.xml"
    

    If the path can vary such as being based on the Environment.SpecialFolder Enum you can incorporate it into the assignment:

    The executing assembly needn't be in the same folder as the xml file.

    0 讨论(0)
提交回复
热议问题