Streamreader - Read Next Line - vb.net

I am new to VB.NET so forgive me if this it a simple question.
I am trying to read the contents of a text file into a Multiline Textbox using the OpenFileFileDialog Box. I am doing this by doing the following:
' Set Properties of OpenFileDialog
With OpenFileDialog1
.FileName = ""
.Title = "Open Text File"
.InitialDirectory = "c:\"
.Filter = "Text files|*.txt"
.ShowDialog()
End With
' Populate Textbox with Selected Text File Contents
txtMain.Text = File.ReadAllText(OpenFileDialog1.FileName)
I then want to read through each line of the file and check the first 3 characters.
If the first 3 characters are "LAX" then I know that the next line of the file should start with "CHI"
So I want to read each line, and if it starts with "LAX" I want to check the next line of the file to make sure that the first 3 characters are "CHI"
If they are not I want to delete any line breaks / carriage returns from the "LAX" line so it brings the next line to the end of this one.
I then want to repeat this task until the first 3 characters of the next line are "CHI"
Basically this ensures that everything relating to LAX is on the same line, as currently this is split over multiple lines in the file.
This is what I've got so far, but I'm stuck with what to do next.
Using streamReader As New StreamReader(OpenFileDialog1.FileName)
While Not streamReader.EndOfStream
Dim line As String = streamReader.ReadLine()
If line.StartsWith("LAX") Then
' Go to end of this line and remove CR or LF. Then repeat the process for the next line down until the next line down starts with "CHI"
End If
End While
End Using
Does this make sense?
Thank you in advance.

My Input (contents of Test.txt)
something1
LAX something2
CHI something3
LAX something4
something5
something6
CHI something7
something8
My Output (contents of TextBox1)
something1
LAX something2
CHI something3
LAX something4 something5 something6
CHI something7
something8
The code
Dim line As String = ""
Using streamReader As New StreamReader(OpenFileDialog1.FileName)
Dim previousLine As String = ""
While Not streamReader.EndOfStream
Dim nextLine = streamReader.ReadLine()
If nextLine.StartsWith("LAX") Or nextLine.StartsWith("CHI") Then
line &= Environment.NewLine & nextLine
previousLine = nextLine
ElseIf previousLine.StartsWith("LAX") Then
line &= " " & nextLine
Else
ine &= Environment.NewLine & nextLine
End If
End While
End Using
TextBox1.Text = line

Instead of iterating over the lines like that, find the index of CHI and fix everything before it, and take everything after it. Does that make sense?
' sample text I made up from your description. correct it if it's wrong
Dim text =
$"LAX{Chr(10)}ABC
D{Chr(10)}EFGH{Chr(13)}I
JCHIKLMNOP
QRST
UVW
XY
Z"
' write it to a file
File.WriteAllText("file.txt", text)
' read it back, the rest of the code would be like yours
Dim textFromFile = File.ReadAllText("file.txt")
Dim indexOfChi = textFromFile.IndexOf("CHI")
Dim result = String.Concat(textFromFile.Take(indexOfChi))
' remove line feeds
result = String.Concat(result.Replace(Chr(10), String.Empty))
' remove carriage returns too (these can be done in one line with vbCrLf or Environment.NewLine)
result = String.Concat(result.Replace(Chr(13), String.Empty))
result &= Environment.NewLine & String.Concat(textFromFile.Skip(indexOfChi))
MessageBox.Show(result)
Admittedly this is not the most efficient code but it seems to work.

Related

How do I remove multiple empty lines in a text file

I wonder if someone is able to help. I have a m3u file with multiple lines of formatted text.
#EXTM3U
#RADIOBROWSERUUID:963194ef-0601-11e8-ae97-52543be04c81
#EXTINF:1,80s80s Christmas
http://streams.80s80s.de/christmas/mp3-192/streams.80s80s.de/
#RADIOBROWSERUUID:9638cfa5-0601-11e8-ae97-52543be04c81
#EXTINF:1,181.FM - Christmas Kountry
http://www.181.fm/stream/pls/181-xkkountry.pls
Whilst I have managed to extract the data into a format that I can need... I am left with multiple blank lines. A sample bit of code I used to Extract the data is...
If line.StartsWith("#EXTM3U") Then 'Remove
lines(i) = ""
End If
If line.StartsWith("#RADIOBROWSERUUID:") Then 'Remove
lines(i) = ""
End If
If line.StartsWith("#EXTINF:1,") Then 'Add # at beginning of line
lines(i) = line.Replace("#EXTINF:1,", "#")
End If
Which then leaves me with the following...
#80s80s Christmas
#http://streams.80s80s.de/christmas/mp3-192/streams.80s80s.de/
#181.FM - Christmas Kountry
#http://www.181.fm/stream/pls/181-xkkountry.pls
I just dont seem to be able to remove the empty/blank lines. I have used google as well as here and non of the answers seem to work for me. Here is the code that I am using...
Dim Newlines As String() = File.ReadAllLines(ofd.FileName)
For t As Integer = 0 To Newlines.Length - 1
Dim line2 As String = Newlines(t)
If line2.StartsWith("") Then ' Remove blank lines
Beep()
Newlines(t) = line2.Replace(Environment.NewLine, String.Empty)
End If
Next
File.WriteAllLines("NewTextm3u.txt", lines)
Can any body see where I am going wrong? Thank you very much.
You can do this:
Dim sFile As String = "c:\test2\test2.txt"
Dim Fdata As New List(Of String)
Fdata = File.ReadAllLines("c:\test2\test.txt").ToList
For i = Fdata.Count - 1 To 0 Step -1
If Fdata(i) = "" Then
Fdata.RemoveAt(i)
End If
Next
For Each sLine As String In Fdata
Debug.Print(sLine)
Next
File.WriteAllLines(sFile)
The above would remove all blank lines
In place of that loop, you could also use lamda expression like this:
Fdata.RemoveAll(Function(MyOneRow) MyOneRow = "")
I used the StrignSplitOptions.RemoveEmptyEntries to get rid of blank lines.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim FileContents = File.ReadAllText("SomeFile.txt")
Dim lines = FileContents.Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
End Sub
As you can see in the above image, there is what we can call an "enter" at the end of the sentence and another one between.
So let's just remove the one between the sentences and because it's just a line you can do it like this:
If line(i) = CHR(13) & CHR(10) then line(i)=""
but if you want to get a little paranoid and just want to remove all the "enters" or "line breaks" just do it like this:
line(i)=Replace(line(i),CHR(13) & CHR(10),"")

String Concatenation with Comma and Single Quotes E.g. ('ABC','DEF','GHI,'JKL')

I've been searching on internet how to Concatenate/Join Single quotes and comma on the String in vb.net's RichTextBox control. Example ('ABC','DEF','GHI,'JKL') I found this code online today it works even there's leading and trailing spaces and even lines are removed but the (' and ') are missing. Can you guys modify the code?
Code:
RichTextBox1.Text = Regex.Replace(RichTextBox1.Text.Trim, "\s+", "','")
Inside the RichTextBox1
ABC
DEF
GHI
JKL
Result: ABC','DEF','GHI','JKL
Desired Result: ('ABC','DEF','GHI','JKL')
As you can see, there are multiple ways this could be done. Here's another:
myRichTextBox.Text = $"('{String.Join("'," & ControlsChars.Lf & "'", myRichTextBox.Lines)}')"
Note that I have used ControlChars.Lf where I would usually use Environment.NewLine because the RichTextBox always uses that line break. I assume that it has something to do with the RTF format and compatibility.
Give this a try
' starting RichTextBox1 contains
' ABC
' DEF
' GHI
' JKL
Dim lns() As String = RichTextBox1.Lines
For x As Integer = 0 To lns.Length - 1
lns(x) = String.Format("'{0}',", lns(x))
Next
lns(0) = "(" & lns(0)
lns(lns.Length - 1) = lns(lns.Length - 1).TrimEnd(","c)
lns(lns.Length - 1) &= ")"
RichTextBox1.Lines = lns
Not knowing how many lines you are dealing with in a real scenario, I chose to use a StringBuilder. It creates mutable (changeable) strings saving us throwing away and recreating strings many times.
Start off the sb with the initial "(". Then the loop uses an interpolated string with an embedded variable for each line. AppendLine will add a new line after the text.
Lastly we display the new string. In .net we can string the dot notation working left to right. First convert the StringBuilder back to an actual String with .ToString. Next we clean up the end of the new string by removing the final comma and the final new line. A new line is actually composed of 2 Chars, carriage return and line feed. Lastly I added the final ")"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lines() = File.ReadAllLines("some text file path")
Dim sb As New StringBuilder
sb.Append("(")
For Each line In lines
sb.AppendLine($"'{line}',")
Next
RichTextBox1.Text = sb.ToString.Trim({","c, Convert.ToChar(13), Convert.ToChar(10)}) & ")"
End Sub

Visual Basic - StreamWriter - How to skip to next line IF said line isn't empty

Hey so I'm trying to do a simple StreamWriter for adding staff information to a text file (I already have a working StreamReader log in page) , the text file has some sample data but also must be able to have new data written to it.
My problem is that ONLY upon initial start up and my initial writing of data the information is written on the same line as the last line of sample data in the text file, not on the next blank line.
Here is how the text file looks after the first attempt to write data after start up.
Jon,Jones
Harry,Potter
James,Gunn
Kieran,Kieranson
Me,TooGreg,
"Me,Too" being my last line of sample data and "Grey,Hardy" being my first data written via StreamWriter
I've done some research on here and found examples of how to write a blank line which you could make the StreamWriter do every time to put spacing in between etc. but that doesn't work here as this problem only occurs the first time on any given start up and if it left a blank line every single time then if I made two attempts to use the StreamWriter it would look like
Jon,Jones
Harry,Potter
James,Gunn
Kieran,Kieranson
Me,Too
Greg,Hardy
BLANK LINE
Tom,Hardy
Which would then enable a blank log in to work.
Here is my code for the StreamWriter
'StreamReader to check if a line is empty or not
Dim StaffReader As StreamReader = File.OpenText("StaffInfo.txt")
strLine = StaffReader.ReadLine()
StaffReader.Close()
'Streamwriter for adding staff log in to textfile
Dim FileCheck As StreamWriter = File.AppendText("StaffInfo.txt")
FileCheck.WriteLine(strStaffUsername2 & "," & strStaffPass2)
FileCheck.Close(``)
MessageBox.Show(strStaffUsername2 & " added to the file. ", "Data Added")
txtUser2.Clear()
txtUser2.Focus()
txtPass2.Clear()
I just want it to skip to the next blank line if the line it is going to write on has any characters on it.
what you are looking for is the point, if the last line in your file contains a carriage return or not. If it does contain a carriage return, then you can append your text with your written code. But if it does not contain a carriage return, you have to prefix your first line with a carriage return.
Thus, first you have to check if your last line has a carriage return. You can do that by a function like this:
Private Function DoesLastLineHasCarriagReturn(Filename As String) As Boolean
Dim s as String = ""
using stream = New StreamReader(Filename)
' we have to read the last two characters
stream.BaseStream.Seek(-2,SeekOrigin.End)
dim c_beforeLast as Integer = stream.Read()
Dim c_Last As Integer = stream.Read()
' if the last character is 10 -> we have a carriage return. Windows and Linux just use different encodings
if (c_Last =10)
If(c_beforeLast = 13)
Console.WriteLine("Ends with carriage return CRLF (Windows)")
Else
Console.WriteLine("Ends with carriage return LF (UNIX, OSX )")
End If
return true
Else
Console.WriteLine("Does not end with Carriage return")
End If
End Using
return false
End Function
Then when beginning to write in the file, first you have to call the function. Here how your code could look like:
If DoesLastLineHasCarriagReturn("StaffInfo.txt")
Dim FileCheck As StreamWriter = File.AppendText("StaffInfo.txt")
FileCheck.WriteLine("Greg" & "," & "Hardy")
FileCheck.Close()
Else
Dim FileCheck As StreamWriter = File.AppendText("StaffInfo.txt")
FileCheck.WriteLine(vbCrLf + "Greg" & "," & "Hardy")
FileCheck.Close()
End If
By the way, I would recommend you to use the using statement to close the stream automatically:
If DoesLastLineHasCarriagReturn("StaffInfo.txt")
Using writer As New StreamWriter("StaffInfo.txt", True)
writer.WriteLine("Greg" & "," & "Hardy")
End Using
Else
Using writer As New StreamWriter("StaffInfo.txt", True)
writer.WriteLine(vbCrLf +"Greg" & "," & "Hardy")
End Using
End If
Since we are dealing with a text file and not doing anything fancy, we can just use the File class in System.IO.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FilePath = "TestFiles/File1.txt"
'Dump contents of file
Dim fileContents As String = File.ReadAllText(FilePath)
'Extract the last 2 characters in the contents
Dim NextToLast As String = fileContents(fileContents.Length - 2)
Dim LastCharacter As String = fileContents(fileContents.Length - 1)
'Check if we have a CrLf an if not add a new line
If Not NextToLast = Chr(13) AndAlso Not LastCharacter = Chr(10) Then
File.WriteAllText(FilePath, Environment.NewLine)
End If
'Write to the file
File.AppendAllLines(FilePath, {TextBox1.Text})
End Sub
To display your text file, add a ListBox to your form.
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'Put the contents of the file into a string array of lines
Dim staff() As String = File.ReadAllLines("TestFiles/File1.txt")
ListBox1.DataSource = staff
End Sub

Search text file for a ranged value

I want to read and write the same file with StreamReader and StreamWriter. I know that in my code I am trying to open the file twice and that is the problem. Could anyone give me another way to do this? I got confused a bit.
As for the program, I wanted to create a program where I create a text if it doesnt exist. If it exists then it compares each line with a Listbox and see if the value from the Listbox appears there. If it doesnt then it will add to the text.
Dim SR As System.IO.StreamReader
Dim SW As System.IO.StreamWriter
SR = New System.IO.StreamReader("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)
SW = New System.IO.StreamWriter("D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt", True)
Dim strLine As String
Do While SR.Peek <> -1
strLine = SR.ReadLine()
For i = 0 To Cerberus.ListBox2.Items.Count - 1
If Cerberus.ListBox2.Items.Item(i).Contains(strLine) = False Then
SW.WriteLine(Cerberus.ListBox2.Items.Item(i))
End If
Next
Loop
SR.Close()
SW.Close()
SR.Dispose()
SW.Dispose()
MsgBox("Duplicates Removed!")
If your file is not that large, consider using File.ReadAllLines and File.WriteAllLines.
Dim path = "D:\temp\" & Cerberus.TextBox1.Text & "_deleted.txt"
Dim lines = File.ReadAllLines(path) 'String() -- holds all the lines in memory
Dim linesToWrite = Cerberus.ListBox2.Items.Cast(Of String).Except(lines)
File.AppendAllLines(path, linesToWrite)
If the file is large, but you only have to write a few lines, then you can use File.ReadLines:
Dim lines = File.ReadLines(path) 'IEnumerable(Of String)\
'holds only a single line in memory at a time
'but the file remains open until the iteration is finished
Dim linesToWrite = Cerberus.ListBox2.Items.Cast(Of String).Except(lines).ToList
File.AppendAllLines(path, linesToWrite)
If there are a large number of lines to write, then use the answers from this question.

adding vertical text each item in text file writeline with some text

I am populating a listbox with some text & saving the output to textfile (sObj.txt)
'Saving items of lb1 in a file under C:\temp
Dim i As Integer
W = New IO.StreamWriter("C:\temp\sObj.txt")
For i = 0 To lb1.Items.Count - 1
W.WriteLine(lb1.Items.Item(i))
Next
W.Close()
This text file contains 3 (for example) entries, let's say abc in 1st line, def in 2nd line & ghi in the 3rd line.
Now I want to append another text file (MPadd.txt) using sObj.txt entries such that I get something like the following:
'Appending listbox items to the file MPadd.txt
Using SW As New IO.StreamWriter("c:\temp\MPadd.txt", True)
SW.WriteLine("some text" & abc & "some text")
SW.WriteLine("some text" & def & "some text")
SW.WriteLine("some text" & ghi & "some text")
End Using
Please help in getting it correctly. thanks.
Just read all the lines from the first file (just three lines so it is not a problem) and then loop over these lines adding prefix and postfix text as you like
EDIT
Following your last example
Dim commands() =
{
"cdhdef -t ftpv2 -c r -f {0} -x ",
"cdhdsdef -v CPUSRG {0} ",
"cacls K:\AES\data\Cdh\ftp\{0}\Archive /E /G OSSUSER:C"
}
Dim counter As Integer = 0
Dim objLines = File.ReadAllLines("C:\temp\sObj.txt")
Using SW As New IO.StreamWriter("c:\temp\MPadd.txt", True)
' Loop only for the number of strings in commands (max 3 now)
for x = 0 to commands.Length - 1
line = objeLines(x).Trim
' This check will prevent empty lines to be used for the output
If line <> string.Empty Then
SW.WriteLine(string.Format(commands(counter), line))
counter += 1
End If
Next
End Using
This example use composite formatting where you define a format string and a progressive placeholder where you want to insert another value.
Of course this will work only if you have just 3 lines in your input file