Save textbox to textfile with proper vbNewLine

prinand

New member
Joined
Dec 16, 2009
Messages
2
Programming Experience
1-3
I noticed a lot of queries / searches regarding saving text to a file and about formatting, but not the proper answer...

when you have a textbox and you save the contents to a file :
VB.NET:
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, TextBox1.Text, False, System.Text.Encoding.ASCII)

and you open the file in notepad, you will see instead of multiple lines one long line and where the vbNewLine should be, a small square symbol. :(

the simple reason is: even if you write a vbNewLine or vbCrLf to your textbox, it will be reduced to vbLf
so when writing the textbox.text to a textfile it only writes the vbLf where you would like to have a vbCrLf

so all you have to do is replace the vbLf with vbNewLine :

VB.NET:
My.Computer.FileSystem.WriteAllText(SaveFileDialog1.FileName, Replace(TextBox1.Text, vbLf, vbNewLine), False, System.Text.Encoding.ASCII)

It puzzled me for a while, so I thought it might be handy to publish....:D
 
The TextBox control doesn't change the linfeed chars of the source text, but if the source text only have vbLf you have to do the replace. The RichTextBox control does however use vbLf (10) exclusively. To save RichTextBox content in plain text format (including correct linefeeds) you can use SaveFile method and specify the format:
VB.NET:
Me.RichTextBox1.SaveFile("FileName.txt", RichTextBoxStreamType.PlainText)
 
you're right (off course...)

:eek: indeed, this is the actual code :

Me.TextBox1 = New System.Windows.Forms.RichTextBox

I was so certain I used a textbox, that I never checked if it was a richtext box, but I did not know a rich textbox behaved in this way.

thanks !
 

Latest posts

Back
Top