且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何保存具有自定义扩展名的表单的内容(非文本或图像)并打开保存的自定义文件

更新时间:2022-12-11 15:41:48

您应尝试创建具有某些属性的类,然后可以使用BinarryFormatter保存该类.您可以将自定义扩展名提供给该类,并通过SaveFileDialog保存它,然后通过OpenFileDialog打开它.

You should try to create a class with some properties then you can save that class using BinarryFormatter. You can give your custom extension to that class and save it through SaveFileDialog and open it by OpenFileDialog.

课程

<Serializable()>
Public Class myGraph
    Private _value1 As String
    Public Property Value1 As String
        Get
            Return _value1
        End Get
        Set(value As String)
            _value1 = value
        End Set
    End Property

    Private _value2 As String
    Public Property Value2 As String
        Get
            Return _value2
        End Get
        Set(value As String)
            _value2 = value
        End Set
    End Property

    Private _value3 As String
    Public Property Value3 As String
        Get
            Return _value3
        End Get
        Set(value As String)
            _value3 = value
        End Set
    End Property
End Class

保存和加载文件的方法

''To Save file
Public Sub SaveFile(GRAPH_1 As myGraph)
    ''To Save File
    Dim dlgSave As New SaveFileDialog
    dlgSave.Filter = "My File|*.grp"
    dlgSave.DefaultExt = ".gpr"
    If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim formatter As New BinaryFormatter
        Using stream As New MemoryStream
            formatter.Serialize(stream, GRAPH_1)
            Using sw As New FileStream(dlgSave.FileName, FileMode.Create)
                Dim data() As Byte = stream.ToArray()
                sw.Write(data, 0, data.Length)
            End Using
        End Using
    End If
End Sub

''To Load fie
Public Function LoadFile() As myGraph
    Dim GRAPH_2 As myGraph = Nothing
    Dim dlgOpen As New OpenFileDialog
    dlgOpen.Filter = "My File|*.grp"
    If dlgOpen.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim formatter As New BinaryFormatter
        Using stream As New FileStream(dlgOpen.FileName, FileMode.Open)
            GRAPH_2 = TryCast(formatter.Deserialize(stream), myGraph)
        End Using
    End If
    Return GRAPH_2
End Function

如何使用文件

''To Save File
Dim GRAPH_1 As New myGraph
With GRAPH_1
    .Value1 = "ABC"
    .Value2 = "XYZ"
    .Value3 = "PQR"
End With

SaveFile(GRAPH_1)


''ToLoad File
Dim GRAPH_2 As myGraph = LoadFile()
If GRAPH_2 IsNot Nothing Then
    ''Place your code here
    ''And assign values to your graph from that (myGraph)class.
End If