Mohmmad Yahya
Mohmmad Yahya

Reputation: 49

how to save text from richtext box to text document in vb.net

I'm taking value from richtextbox and i want to save it in new text document Value how I want to save in text document

How it stores it

I Want to save text of rich text box in text document as i write in rich text box but it stores like shown in image

My Code

Using Sw As StreamWriter = File.CreateText(path)
            Dim number As String = RichTextBox1.Text
            Sw.WriteLine(number)

        End Using

Please help

Upvotes: 0

Views: 1421

Answers (2)

Visual Vincent
Visual Vincent

Reputation: 18310

The problem here is that both the TextBox and the RichTextBox control uses LF (Line Feed) as their newline format, but Windows's newline format is actually CR + LF (Carriage Return + Line Feed), which is what Notepad expects it to be.

The line breaks are there, Notepad just doesn't render them.

To fix this you can either replace all LFs with Environment.NewLine (which adapts to the current system) before saving:

Dim number As String = RichTextBox1.Text.Replace(vbLf, Environment.NewLine)
Sw.Write(Number)

...or you can save it line-by-line instead using the StreamWriter.WriteLine() method (which uses CR + LF for line breaks):

Using Sw As StreamWriter = File.CreateText(path)
    For Each Line As String In RichTextBox1.Lines
        Sw.WriteLine(Line)
    Next
End Using

Read more:

Upvotes: 3

lcryder
lcryder

Reputation: 496

After each Write, perform .Write(Environment.NewLine)

Upvotes: 0

Related Questions