VB.NET序列化和保存

时间:2014-07-10 20:50:32

标签: xml vb.net save

我创建了一个包含一些文本框的表单,需要在VB.net中序列化为XML文件。

一切都好,因为保存部分。我只能得到一个编写器/阅读器来创建一个单独的文件,每次有人使用计费应用程序时都会被替换,但我想使用Savefile对话框将序列化文件保存在其他地方,我想用openfile对话框打开它们,而不是使用流

以下是代码:

'

Public Structure User
    Public UserName As String
    Public PassWord As String
    Public StreetAddress As String
    Public City As String
    Public State As String
    Public Zip As String
End Structure
Private Function CreateRecord() As User
        Dim r As User

        With r
            .UserName = TextBox1.Text
            .PassWord = TextBox2.Text
            .StreetAddress = TextBox3.Text
            .City = TextBox4.Text
            .State = TextBox5.Text
            .Zip = TextBox6.Text
        End With

        Return r

    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim ser As New XmlSerializer(GetType(User))
        Dim fs As New FileStream("c:\userrecord.txt", FileMode.Create)

        ser.Serialize(fs, CreateRecord())

        fs.Close()


    End Sub
Private Sub LoadIntoTB(ByVal rec As User)

        With rec
            TextBox1.Text = .UserName
            TextBox2.Text = .PassWord
            TextBox3.Text = .StreetAddress
            TextBox4.Text = .City
            TextBox5.Text = .State
            TextBox6.Text = .Zip
        End With


    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim ser As New XmlSerializer(GetType(User))
        Dim fs As New FileStream("c:\userrecord.txt", FileMode.OpenOrCreate)
        Dim rec As User

        rec = DirectCast(ser.Deserialize(fs), User)

        LoadIntoTB(rec)
        fs.Close()
    End Sub

如何用Save file对话框和openfile对话框替换FileStream?

1 个答案:

答案 0 :(得分:0)

你不能替换FileStream本身,它是wrties实际文件的类。您想要替换传递给构造函数的文件名变量。

所有打开(和保存)FileDialog都有效地将字符串设置为用户选择的文件路径。

您需要做的就是声明类和(设置您想要的任何属性,例如文件类型等),然后调用.ShowDialog

可在此处阅读文档: http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog%28v=vs.110%29.aspx http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog%28v=vs.110%29.aspx

BTW使用代码,wiothout归属,很糟糕.... http://www.vbforums.com/showthread.php?616479-How-do-I-save-multiple-textboxes-to-a-single-file-and-load-each-one-by-itself&p=4172754#post4172754