Hard Time Writing NewLine in a .TXT File - vb.net

Basically what I am doing is writing a program that pulls a quote from a website and writes it to a .txt file. It works fine except that I have no idea who to add NewLine into the .txt file. I will just show you the code.
If Not div Is Nothing Then
Dim blank As String = Environment.NewLine
Dim finish As String = (div.InnerText.Trim())
TextBox2.Text = Chr(34) & finish & Chr(34)
Dim fileName As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt")
My.Computer.FileSystem.WriteAllText(fileName, Chr(34) & finish & Chr(34), True)
My.Computer.FileSystem.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("userprofile"), "Documents\Horoscope\Monthly.txt"), blank, True)
My.Computer.FileSystem.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("userprofile"), "Documents\Horoscope\Monthly.txt"), blank, True)
End If
Now that works fine for the first pair of quotes, but anything after it does not indent due to another section of code that I have that deletes duplicates.
Dim lines As String() = IO.File.ReadAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"))
lines = lines.Distinct().ToArray()
IO.File.WriteAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"), lines)
Is there another way that I can get the same affect of having a gap inbetween my quotes in a text file?

When removing the duplicates, you can drop the existing blank lines with Where, then add them back into the lines array using SelectMany:
lines = lines.
Where(Function(x) Not String.IsNullOrEmpty(x)).
Distinct().
SelectMany(Function(x) { x, String.Empty }).
ToArray()
The SelectMany returns the line, plus a blank, for each line left after the Distinct.
You may also want to use File.AppendAllLines when adding new entries - seems a little cleaner:
File.AppendAllLines(fileName, { Chr(34) & finish & Chr(34), ""})
EDIT
This would fit in with your code something like this:
If Not div Is Nothing Then
Dim finish As String = (div.InnerText.Trim())
TextBox2.Text = Chr(34) & finish & Chr(34)
Dim fileName As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt")
IO.File.AppendAllLines(fileName, { Chr(34) & finish & Chr(34), ""})
End If
'...
Dim lines As String() = IO.File.ReadAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"))
lines = lines.
Where(Function(x) Not String.IsNullOrEmpty(x)).
Distinct().
SelectMany(Function(x) { x, String.Empty }).
ToArray()
IO.File.WriteAllLines(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Horoscope", "Monthly.txt"), lines)

Related

Read message from text file and display in message box in vb.net

JavaError.128 = "project creation failed. & vbLf & Please try again and if the problem persists then contact the administrator"
I am able to read this message from text file. the issue is vbLf is not considered as newline in msgbox. it prints vbLf in msgbox.
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(errorfilePath)
While ((sr.Peek() <> -1))
line = sr.ReadLine
If line.Trim().StartsWith("JavaError." & output) Then
isValueFound = True
Exit While
End If
End While
sr.Close()
End Using
If isValueFound Then
Dim strArray As String() = line.Split("="c)
MsgBox(strArray(1).Replace("""", "").Trim({" "c}))
End If
You can make all your code a simpler one line version using File.ReadAllLines and LINQ. This code will put all the lines starting with javaerror into the textbox, not just the first:
textBox.Lines = File.ReadAllLines(errorFilePath) _
.Where(Function(s) s.Trim().StartsWith("JavaError")) _
.Select(Function(t) t.Substring(t.IndexOf("= ") + 2).Replace(" & vbLf & ", Environment.NewLine)) _
.ToArray()
You need to Imports System.IO and System.Linq
This code reads all the lines of the file into an array, then uses LINQ to pull out only those starting with java error, then projects a new string of everything after the = with vbLf replaced with a newline, converts the enumerable projection to an array of strings and assigns it to the textBox lines
If you don't want all the lines but instead only the first:
textBox.Text = File.ReadLines(errorFilePath) _
.FirstOrDefault(Function(s) s.Trim().StartsWith("JavaError")) _
?.Substring(t.IndexOf("= ") + 2).Replace(" & vbLf & ", Environment.NewLine))
This one uses ReadLine instead of ReadALlLines - ReadLines works progressively, and it makes sense to be able to stop reading after we foundt he first rather than have the overhead of reading ALL (million) lines only to then end up pulling the first out and throwing 999,999 lines of effort away. So it's reading line by line, pulls out the first that starts with "JavaError" (or Nothing if there is no such line), then checks if Nothing came out (the ?) and skips the Substring if it was Nothing, or it does a Substring on everything after the = and replaces vbLf with newline
For a straight up mod of your original code:
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(errorfilePath)
While ((sr.Peek() <> -1))
line = sr.ReadLine
If line.Trim().StartsWith("JavaError." & output) Then
isValueFound = True
line = line.Replace(" & vbLf & ", Environment.NewLine))
'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ added code
Exit While
End If
End While
sr.Close()
End Using
If isValueFound Then
Dim strArray As String() = line.Split("="c)
MsgBox(strArray(1).Replace("""", "").Trim({" "c}))
End If
Note that I've always made my replacement on & vbLf & with a space at each end to avoid stray spaces being left behind - if your file sometimes doesn't have them, consider using Regex to do the replace, e.g. Regex.Replace(line, " ?& vbLf & ?", Environment.NewLine
This could work:
Dim txtFile As String = "project creation failed. & vbLf & Please try again and if the problem persists then contact the administrator"
Dim arraytext() As String = txtFile.Split("&")
Dim txtMsgBox As String = Nothing
For Each row As String In arraytext
If Trim(row) = "vbLf" Then
txtMsgBox = txtMsgBox & vbLf
Else
txtMsgBox = txtMsgBox & Trim(row)
End If
Next
MsgBox(txtMsgBox)

VBNet Reading csv file - separating column in a row - comma delimited

This has been bugging me for a week and i do not see any other way. We have only been taught record data structures which is basic, FileOpen, WriteLine and etc. but i read MSDN and StreamWriter/Reader looks much more promising. This is an assignment/coursework and its essential for practically all parts of the program.
All i want to do is read line by line separating fields by a comma and define it as a variable. It would also help to be able to read the line without the quotes "", because right now when i read a password out with LineInput it reads it entirely "pass".
Private Sub StudentLogin()
Dim Filename As New StreamWriter("" & Register.StudentDirectory & "" & Username & ".txt")
Dim str As String = "This"
Dim lines() As String = str.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Firstname = columns(0)
Surname = columns(1)
Password = columns(2)
ClassID = columns(3)
Next
MessageBox.Show("" & ClassID & " " & Password & "")
End Sub
Text file:
"cem","polat","pass","class"
I just want to read the file - then each line, row by row, defining each column field which is in C:/Spellcheck/data/accounts/students/+filename+ and define a few variables.

Find and replace running in a never ending loop

I am currently using this code snippet in my script for replacing text in an ASCII file
Dim fso, inputFile, outputFile
Dim str As String
Const quote As String = """"
Dim MyFile As String = Folder & "\client-1\com\company\assembleegameclient\parameters\Parameters.class.asasm"
fso = CreateObject("Scripting.FileSystemObject")
inputFile = fso.OpenTextFile(MyFile, 1)
str = inputFile.ReadAll
str = Replace(str, quote & TextBox1.Text & quote, quote & TextBox3.Text & quote)
outputFile = fso.CreateTextFile(MyFile, True)
outputFile.Write(str)
System.Threading.Thread.Sleep(5000)
I put the threading at the end of the to see if it would fix the problem by waiting, but it doesn't work. The next step in the script requires this portion to be completely finished before proceeding. Is there a way to attach this to a process with waitforexit? or something similar that works on strings?
It would be optimal if it would output the number of changes that were made and that it was complete.

Get Text between characters in a string

I have a text file with a list of music that looks like this:
BeginSong{
Song Name
Artist
Genre
}EndSong
There are multiple instances of this.
I'm wanting to get the text between the BeginSong{ and }EndSong and put the song info
into a string array. Then I want to add each instance to a ListBox as Artist - Song Name
(that part I'm sure I can figure out though). I hope that was a clear description.
Use the ReadLine() function of the FileStream
since you already know the order of the information, you should be able to loop all File Lines and store them in their corresponding properties.
Pseudo:
WHILE Reader.Read()
Store Line in BeginSongTextVariable
Read Next Line
Store Line in SongNameVariable
Read Next Line
Store Line in ArtistNameVariable
Read Next Line
Store Line in GenreVariable
Read Next Line
Store Line in EndSongTextVariable
Add The Above Variables in List
End While
You can use a regular expression with named groups:
BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong
Something like this:
Imports System.Text.RegularExpressions
'...
Dim s As New Regex("BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong")
Dim mc As MatchCollection = s.Matches(inputFile)
For Each m As Match In mc
Dim song_name As String = m.Groups("song_name").Value
Dim artist As String = m.Groups("artist").Value
Dim genre As String = m.Groups("genre").Value
'use or store these values as planned
Next
There is a nice answer from Neolisk that uses Regular Expressions. But since you also included the VB6 tag in addition to VB.NET, I'll take a shot at a VB6 solution.
You can use the string Split function, and split on the "ends", i.e. "BeginSong{" and "}EndSong"
Dim songInfos As String
Dim firstArray() As String
Dim secondArray() As String
Dim thirdArray() As String
Dim songInfoArray() As String
Dim i As Integer
Dim songCounter As Integer
' to test:
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name1" & vbNewLine
songInfos = songInfos & "Artist1" & vbNewLine
songInfos = songInfos & "Genre1" & vbNewLine
songInfos = songInfos & "}EndSong" & vbNewLine
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name2" & vbNewLine
songInfos = songInfos & "Artist2" & vbNewLine
songInfos = songInfos & "Genre2" & vbNewLine
songInfos = songInfos & "}EndSong"
firstArray = Split(songInfos, "BeginSong{")
songCounter = 0
ReDim songInfoArray(2, 0)
For i = 1 To UBound(firstArray) Step 1
secondArray = Split(firstArray(i), "}EndSong")
thirdArray = Split(secondArray(0), vbNewLine)
songInfoArray(0, songCounter) = thirdArray(1)
songInfoArray(1, songCounter) = thirdArray(2)
songInfoArray(2, songCounter) = thirdArray(3)
songCounter = songCounter + 1
If i < UBound(firstArray) Then
ReDim Preserve songInfoArray(2, songCounter)
End If
Next i
The watch after the last line. Note the structure of songInfoArray, which was required for it to be ReDimmed

How to read Different lines of text in a RichTextBox

I want to know how to read and convert the different lines of a richtextbox in vb.net
for example if these are the lines of a RichTextBox:
Hello
Hi
How can I convert it to something like:
Yo(Hello)
Yo(Hi)
and put the result in a second richtextbox?
RichtextBox has a lines property:
Dim rtb_in As New RichTextBox
Dim rtb_out As New RichTextBox
For Each line In rtb_in.Lines
rtb_out.AppendText(String.Format("Foo({0})", line))
Next
Always a good idea to check out MSDN for the classes you work with ...
You could try splitting on a new line and modifying the results:
Dim box1Lines as String() = richTextBox1.Text.Split(new String() { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
Dim newLines as String = ""
For Each line As String in box1Lines
newLines += "Yo(" & line & ")" & Environment.NewLine
Next
richTextBox2.Text = newLines
Possibly you should use String.Join to accomplish it. A one line solution would be:
rtbOut.Lines = ("Yo(" & String.Join(")" & Environment.NewLine & "Yo(", rtbIN.Lines) & ")").Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
and here is the complete code where modified line is assigned to second RichTextBox:
Dim rtbIN As New RichTextBox
Dim rtbOut As New RichTextBox
rtbIN.Lines = New String() {"Hello ", "Hi"}
rtbOut.Lines = ("Yo(" & String.Join(")" & Environment.NewLine & "Yo(", rtbIN.Lines) & ")").Split(Environment.NewLine.ToCharArray, StringSplitOptions.RemoveEmptyEntries)