Limtyty
Limtyty

Reputation: 21

How to save/load data from RichTextBox to/from file

I have Richtextbox to input text with multiple font names, color, backcolor and size.

I want to save it and load it with the same setting.

Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
    SaveFileDialog1.Filter = "TextFile (*.txt;*.rtf)|*.txt;*.rtf|Batch File (*.bat)|*.bat|All Files (*.*)|*.*"
    SaveFileDialog1.FileName = "Untitled"
    If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim a() As String = SaveFileDialog1.FileName.Split("\")
        Dim sw As New StreamWriter(SaveFileDialog1.FileName)
        sw.Write(RichTextBox1.Text)
        My.Settings.Save()
        sw.Close()
    End If
End Sub

Upvotes: 0

Views: 18343

Answers (3)

Mir Rahed Uddin
Mir Rahed Uddin

Reputation: 1406

There is a difference between Save and Save As

Code for Save

 Private Sub SaveToolStripMenuItem_Click(sender As Object, e AsEventArgs) Handles SaveToolStripMenuItem.Click

 If Me.Text = "Untitled" Then

            Try
                 RichTextBox1.SaveFile(OpenFileDialog1.SafeFileName)
                 RichTextBox1.Modified = False
             Catch ex As Exception
                SaveAsToolStripMenuItem.PerformClick()
             End Try
         ElseIf Me.Text = OpenFileDialog1.SafeFileName Then
             Try
                 RichTextBox1.SaveFile(OpenFileDialog1.FileName)
                 RichTextBox1.Modified = False
             Catch ex As Exception
                 SaveAsToolStripMenuItem.PerformClick()
            End Try
        ElseIf Me.Text = SaveFileDialog1.FileName Then
            Try
                 RichTextBox1.SaveFile(SaveFileDialog1.FileName)
                 RichTextBox1.Modified = False
            Catch ex As Exception
                 SaveAsToolStripMenuItem.PerformClick()
            End Try
  End If

End Sub

Code for Save As

Private Sub SaveAsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveAsToolStripMenuItem.Click

        Try
            If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                RichTextBox1.SaveFile(SaveFileDialog1.FileName)
                Me.Text =SaveFileDialog1.FileName
                RichTextBox1.Modified = False
            End If
        Catch ex As Exception
            MsgBox("The file cannot be saved", MsgBoxStyle.Critical, "Save")
        End Try

 End Sub

Upvotes: 0

Benjli
Benjli

Reputation: 125

You can use this code for reading:

RichTextbox1.text = System.IO.File.ReadAllText(openfilepath)

And this for writing:

System.IO.File.WriteAllText(Savefiledialog1.FileName, Richtextbox1.text)

Hope it will help.

Upvotes: 2

Related Questions