rich textbox combines all lines into one when saved as txt file? - vb.net

I have a rich textbox in vb.net, which contains several lines of text however when I try and save the text to a .txt file all the lines are combined into one???
How can I overcome this?
what i did try was:
Dim MYLINES As Object
For Each MYLINES In RichTextBox1.Text
objWriter.WriteLine(MYLINES.ToString & Environment.NewLine)
Next
objWriter.Close()
however this simply placed every single character on a difrent line...

Save it as a .RTF file (instead of .TXT), wich can process the line breaks directly. Thats an option.
Or you can wirte the lines individually:
Dim sw As New System.IO.StreamWriter(sFileName)
For Each sLine as String in TextBox1.Lines
sw.WriteLine(sLine)
Next
sw.Close()
The method WriteLine already adds a line break at the end. It more or less the same as:
.Write(sLine & Enviroment.NewLine())

Related

Trying to close textfile after line is read

Im trying to output the data from the second line of my textfile to a datagridview but when doing so it is also outputting every line after the the second line. This is what I have tried. Thanks
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
For index = 1 To lines.Length - 1
Dim cells = lines(index).Split(","c)
dgvOutput.Rows.Add(cells)
FileClose()
It's outputting every line after the second line, because that's what you're telling it to do when you iterate through the array of strings returns from ReadAllLines.
IO.File.ReadAllLines does not leave an output stream open. The file is closed. What it does do, is return a zero-based (by default) array of the contents of the file, with line breaks being the delimiter for the split.
To just get the contents of the second line, using ReadAllLines, this is what you need:
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
If lines.length >= 2 Then
Dim cells = lines(1).Split(","c)
dgvOutput.Rows.Add(cells)
End If
Now, that does have the overhead of reading the entire file in. If you open the file using a reader object, then you only need to read the first and second lines of the file to get that second line.
That would be something like this:
Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(OrderId & ".txt")
Dim a as String
' This reads the first line, which we throw away
reader.ReadLine()
a = reader.ReadLine()
reader.Close()
Dim cells = a.Split(","c)
dgvOutput.Rows.Add(cells)
You would need to test your explicit circumstances to determine which is better for what you're trying to do.
Your loop is executed over all lines skipping just the first line.
While I cannot see what happen in the FileClose call it seems to not have any sense because ReadAllLines has already closed the file.
You can get the second line of your file with a single line of code
Dim line as String = File.ReadLines(OrderID & ".txt").Skip(1).Take(1).FirstOrDefault()
' this check is required to avoid problems with files containing 0 or 1 line
if line IsNot Nothing Then
Dim cells = line.Split(","c)
dgvOutput.Rows.Add(cells)
End If
Notice that I have replaced the ReadAllLines with ReadLines. This is better because using this method you don't read all lines when you need only the second one (if it exists). More info at ReadLines vs ReadAllLines
Dim lines = IO.File.ReadAllLines(OrderID & ".txt")
Dim SecondLine = lines(1)
File.ReadAllLines opens and closes the file for you so there is not need to add code to close it.

Visual Basic Append to a specific point in a text file

I am currently trying to manipulate a line in a file that we are using to retain data, using comma delimiters. For example -
121,1212, XJAY,Sean K,Kean S,AAAA-BBBB-AAAA-BBBB-AAAA
12456,987654,WYST,Steve Jobs,Bill Gates,CAAA-BBBB-AAAA-BBBB-AAAA
If I assume that the last line is always a unique code, is it possible to identify that line in the text file and append it with another field?
Prior research has been reading through the APIs for StreamReader and StreamWriter, and looking through other StackOverflow questions, however most questions seem focused on just appending to the end of the file, or in different languages!
As always thank you for your time, and if there is anything I've left off please let me know!
You can't manipulate a line in a file in any reasonably easy way.
There are no methods to work with lines in a file, because files are not line based. They are not even character based. The bytes in the file are decoded into characters, then the line break characters are recognised and the characters can be split into lines.
The easiest way to manipulate a line is to read the entire file into a string array, change the string that you want change, then write the entire string array to the file.
Example:
Dim fileName As String = "c:\data.txt"
Dim lines As String() = File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Length - 1
Dim line As String = lines(i)
If line.StartsWith("12456,") Then
lines(i) = line & ",More data"
End If
Next
File.WriteAllLines(fileName, lines)
If you are looking for a way to parse Each line with StreamReader and StreamWriter: Here it is:
'You will need Imports System.IO
Dim TheNewFile As String
Dim MyLine As String
Dim MyStream2 As New FileStream("C:\Your Directory\YourFile.txt", FileMode.Open)
Dim MyReader As New StreamReader(MyStream2)
Dim MySettings As New StringReader(MyReader.ReadToEnd)
MyReader.BaseStream.Seek(0, SeekOrigin.Begin)
MyReader.Close()
MyStream2.Close()
Try
Do
MyLine = MySettings.ReadLine
'This if statement is an exit parameter. It can be if it contains or if 5 consecutive lines are nothing. It could be a number of things
If MyLine Is Nothing Then Exit Do
'This is the file you will write. You could do if MyLine = "Test" Then ........... append whatever and however you need to
TheNewFile = TheNewFile & MyLine & vbCrLf
Loop
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'-----------------Write The new file!!!----------------
Dim MyStream3 As New FileStream("C:\Where you want to write New File\NewFileName.txt", FileMode.Create)
Dim MyWriter3 As New StreamWriter(MyStream3)
MyWriter3.Write(TheNewFile & "Test")
MyWriter3.Close()
MyStream3.Close()

Reading text file and skipping blank lines in vb.net

I have the below code which appends the content of a text file to my RichTextBox1.
Dim FileName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CLIENT HISTORY\" & TextBox1.Text))
For Each ClientDetailsCHT As FileInfo In FileName.GetFiles("*.CHT", SearchOption.TopDirectoryOnly)
RichTextBox1.AppendText(File.ReadAllText(ClientDetailsCHT.FullName))
Next
' Send to printing sub
This works fine.
The problem I am having is that this text file sometimes contains blank lines and I would like to skip those blank lines so that the code only appends text to the RichTextBox.
How can I re-write my code to achieve this? I am using Visual Basic 2010.
You can loop through the lines and skip the ones that are blank. The following code skips lines that are empty or only contain white space. If you only want to skip empty lines, change IsNullOrWhiteSpace to IsNullOrEmpty.
Dim FileName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CLIENT HISTORY\" & TextBox1.Text))
For Each ClientDetailsCHT As FileInfo In FileName.GetFiles("*.CHT", SearchOption.TopDirectoryOnly)
For Each line As String In File.ReadAllLines(ClientDetailsCHT.FullName)
If Not String.IsNullOrWhiteSpace(line) Then RichTextBox1.AppendText(line & vbCrLf)
Next
Next
' Send to printing sub

replace text in richtext box quickly

i'm trying to load a text file to richtextbox using this codes
RichTextBox1.Text = My.Computer.FileSystem.ReadAllText("path")
RichTextBox1.LoadFile("path", RichTextBoxStreamType.PlainText)
but both of them take time to load the file ,, the file size is around 400-1MB
so how to load it more quickly?
and with my code after loading the textfile i use this code
RichTextBox1.Text = Replace(RichTextBox1.Text, "text", "othertext")
but the problem is this take alot of time !!
How to do it quickly and save time :) , thanks!
You can cut the time almost in half by using an ordinary string variable instead of RichTextBox1.Text in the Replace function:
s = My.Computer.FileSystem.ReadAllText("path")
s = s.Replace("text", "othertext")
RichTextBox1.Text = s
You can combine these into one or two statements, but separating them allows you time each operation. The time-consuming part is accessing the RichTextBox control.
You could try reading it line-by-line:
Using Reader As New IO.StreamReader("<File Path>")
Do Until Reader.EndOfStream
Dim Line As String = Reader.ReadLine()
Line = Replace(Line, "text", "othertext")
RichTextBox1.AppendText(Line & Environment.NewLine)
Loop
End Using

VB.Net Writing to Txt File

I'm trying to write the content of my textbox to a txt file.
My code works fine but my error is, when I open txt file I see
writeline1writeline2writeline3
instead of
writeline1
writeline2
writeline3
my code;
result As List(Of String) = New List(Of String)
convertedText.Lines = result.ToArray()
My.Computer.FileSystem.WriteAllText(mypath & "\convertedcontent.txt", convertedText.Text, False)
Writing to .csv and many other file types work fine but I don't know how to break lines for text file.
Thanks in advance
I would use System.IO.File.WriteAllLines:
Dim path = System.IO.Path.Combine(mypath, "convertedcontent.txt")
System.IO.File.WriteAllLines(path, result)
Otherwise you need to append Environment.NewLine to each line, you can use String.Join:
System.IO.File.WriteAllText(path, String.Join(Environment.NewLine, result))
You need to add & vbCrLf to your strings (each line)
Not sure where you are getting your strings from.. but you will have to add the carrier return/Line Feed character to those strings, one at the end of every string.
Might just even loop through your array and add them there?
P.S. Some of the comments have quicker ways of getting there, but this is probably what happens behind the scenes...
for i = 0 to convertedText.Lines.count -1
convertedText.Lines(i) += vbCrLf
next