Reading text file and skipping blank lines in vb.net - 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

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()

I can't get my program to read the second line of a text document

Alright so I am trying to make my program read a specific line of a text file. I created two labels, designated one as TheFileName and the other as TheText. Everything works, except I can not figure out how to make it read the second line, and only the second line.
Code:
Dim Rlo As New IO.StreamReader("C:\Users\Alex\Documents\Visual Studio 2012\Projects\RobloxRecruitV1\RobloxRecruitV1\bin\Debug\" & TheFileName.Text & ".txt")
TheText.Text = Rlo.ReadLine(2)
Dim Rlo As New IO.StreamReader("C:\Users\Alex\Documents\Visual Studio 2012\Projects\RobloxRecruitV1\RobloxRecruitV1\bin\Debug\" & TheFileName.Text & ".txt")
Dim firstLine As String
'read first line
firstLine = Rlo.ReadLine()
'read secondline
TheText.Text = Rlo.ReadLine()

rich textbox combines all lines into one when saved as txt file?

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())

Delete line in TXT file but keep everything else

Hey all i am trying to figure out a way to delete something inside a text file but keep everything around it.
An example of this would be:
SDfmifgn349234024jn4tnge0b04tnEFGm34tmn34t0egonkerglnk
318erg4nergpERGhmboergn4t34tmg054
fg94t34tskmsdglnEGgjr894ERG94mrg34tSDFS$45352ty
GGreerkg0gm4m505556g0fdg6555fbd105f1g
And say i wanted to delete the 318erg4nergpERGhmboergn4t34tmg054 and therefore it would turn out to be saved as:
SDfmifgn349234024jn4tnge0b04tnEFGm34tmn34t0egonkerglnk
fg94t34tskmsdglnEGgjr894ERG94mrg34tSDFS$45352ty
GGreerkg0gm4m505556g0fdg6555fbd105f1g
But i am unable to find out how to go about doing that!
I've tried this code below that i found:
Dim dir As New DirectoryInfo(defaultNetworkDrive)
For Each file As FileInfo In dir.GetFiles()
If file.Extension = ".txt" Then
Dim ioFile As New StreamReader(defaultNetworkDrive & file.Name)
Dim ioLine As String ' Going to hold one line at a time
Dim ioLines As String ' Going to hold whole file
ioLine = ioFile.ReadLine
ioLines = ioLine
While Not ioLine = ""
ioLine = ioFile.ReadLine
ioLines = ioLines & vbCrLf & ioLine
End While
MsgBox(ioLines) 'SHOWS all the lines in the TXT file
If InStr(1, ioLines, encryptedText, vbTextCompare) <> 0 Then
MsgBox("True")
Else
MsgBox("False")
End If
'Dim sw As StreamWriter = file.CreateText("input.txt")
'sw.Write(ioLines)
'sw.Close()
ioFile.Close()
End If
Next
I do find it and its TRUE but i am not sure how to go about just deleting that line then saving it!
Any help would be great! :o)
David
You have to rewrite the file. Use StreamWriter to create a temporary file. Read one line at a time and write it to the output file. Skip the write if you don't want the line. Clean up by renaming the original, renaming the temporary then deleting the renamed original.
Use something better than a text file, like a dbase, if this is too slow.
You need to check for the string to exclude inside the loop where you read the lines:
While Not ioLine = ""
ioLine = ioFile.ReadLine
If ioLine <> "318erg4nergpERGhmboergn4t34tmg054" then
ioLines = ioLines & vbCrLf & ioLine
End
End While
If ioLines.StartsWith(encryptedText) Then
MsgBox("True")
Else
MsgBox("False")
End If
You are checking if the 'file' (ioLines) starts with the encrypted text, not the line (ioLine). I suspect that's why it isn't finding it.
I'm not sure if you are intending it, but I think adding the vbCrLf to ioLines will cause an empty line between each line. So your file output would be
LINE
[empty line]
LINE
[empty line]
...
To save the file without that line, you would need to write the lines you want to save to a new file.
Read line from file
If not excluded line
write line
Something like that (obviously off the top of my head) :)
Hmm, maybe I found the answer.
You are connecting all lines together:
ioLines = ioLines & vbCrLf & ioLine
Later you are trying to find the search string, but only at the start of the combined line!
ioLines.StartsWith(encryptedText)
This would only find the encryptedText if it be appear on the very first line of the file.
In your example the relevant string is somewhere in the middle of the iolines string.
So you should try to use
ioLines.Contains(encryptedText)
instead.
Edit:
You could try to do the following (just a though, I haven't tested it)
Dim fileLines as List(Of String)
fileLines = new List(Of String)(File.ReadAllLines(yourFileNameHere))
For i as Integer = fileLines.Count To 0 Step -1
If fileLines(i).Contains(encryptedText) Then
fileLines(i).RemoveAt(i)
End If
Next
File.WriteAllLines(yourFileNameHere, fileLines.ToArray)
HTH