Is it possible to create a custom file type for a program in VB

advertisements

Is it possible to have a custom file type that would open in a VB program.

For example: There is a text box with some text and a check box that's checked... You would save to a custom file type and when you opened the file up again, the check box would be checked and the text box would have the text. It would basically save the state of the program to a custom file type.

E.g. -> .pro, .lll, .hgy, .xyz, .abc

I'm just curious... is this possible and if so, how would I approach this?


You can do what Ichiru states with a BinaryWriter and BinaryReader which I have done with some of my projects before using an in Memory datatable and serializing it.

Imports System.IO

Public Class Form1

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

        Using bs As New BinaryWriter(File.Open("Mydata.xyz", FileMode.Create))
            bs.Write(TextBox1.Text)
            bs.Write(CheckBox1.Checked)
            bs.Close()
        End Using
    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        If File.Exists("Mydata.xyz") Then
            Using br As New BinaryReader(File.Open("Mydata.xyz", FileMode.Open))
                Try
                    TextBox1.Text = br.ReadString
                    CheckBox1.Checked = br.ReadBoolean
                Catch ex As EndOfStreamException
                    'Catch any errors because file is incomplete
                End Try
            End Using
        End If
    End Sub
End Class

But .Net has a built in Settings Class that you can use to persist your Data. It would be used like this

Public Class Form1

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        My.MySettings.Default.checkbox1 = CheckBox1.Checked
        My.MySettings.Default.textbox1 = TextBox1.Text
        My.MySettings.Default.Save()
    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.

        CheckBox1.Checked = My.MySettings.Default.checkbox1
        TextBox1.Text = My.MySettings.Default.textbox1

    End Sub
End Class