Read message from text file and display in message box in vb.net - 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)

Related

VB.NET 2010 Express "NotSupportException" unhandled

I've been working on a script, a windows console application, that reads a .CSV for a file-path and other various information and then using System.IO.File.Copy to copy the file to a new directory and give it a new name. The file's im working with are .WAV files. Essentially I take a peek at the .CSV provided, then grab the filepath from there, then rename the file using different columns from the .CSV with dot-notation. I.E. Acc.Date.Name.Type.wav.
However, I'm experiencing "NotSupportedException" error on the line that copies and create the new file. The sub message is "The given paths format is not supported." Now, I've fairly new to VB code, I' assuming right now that .WAV format is not supported.
I'm not sure what all to add, if anything is needed let me know.
Here is the script so far:
Module Module1
Sub Main()
Dim fileLine As String
Dim aryTextFile() As String
Dim objReader As New System.IO.StreamReader("C:\Temp\EDCallFilePaths.csv")
Do While objReader.Peek() <> -1
fileLine = fileLine & objReader.ReadLine() & vbNewLine
aryTextFile = fileLine.Split(",")
If Not aryTextFile(7) = "null" Then
System.IO.File.Copy(aryTextFile(7), "C:\Temp\" & aryTextFile(0) & "." & aryTextFile(2) & "." & aryTextFile(3) & "." & aryTextFile(4) & "." & aryTextFile(5) & "." & aryTextFile(6) & ".wav")
fileLine = ""
End If
Loop
End Sub
End Module
I should note, column 7 is the filepath to the recording

Hard Time Writing NewLine in a .TXT File

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)

Prevent the `vbLf` being included in a `String.Length` calculation

I have a Collection of servers which I take from a multiline textbox.
I have some simple validation which should be trimming whitespace (to prevent an entry being created for blank line), but it's not working.
For example, if Me.formServers.txtServers.Text is as follows, the lengths of the lines are returned as 5, 5, 5 and 4. How can I correctly calculate the length of each line and thus avoid erroneous items being added to my Collection? Thanks.
TTSA
TTSB
TTSC
TTSD
Here is my code
Me.Servers = New Collection ' Reset 'Servers' to ensure only the correct servers are included
For Each Server As String In Me.formServers.txtServers.Text.Split(vbLf)
If Not Server.Trim.Length = 0 Then Me.Servers.Add(Server)
MsgBox(Server.Length)
Next
This test was interesting:
Dim s As String = "TTSA" & vbCrLf
s &= "TTSB" & vbLf
s &= "TTSC" & vbCr
s &= "TTSD" & Environment.NewLine
s &= "TTSE" & vbNewLine
Dim Excluded() As String
Excluded = s.Split({vbCrLf, vbLf}, StringSplitOptions.None)
For Each s In Excluded
Debug.Print(s & " " & s.Length)
Next
result:
TTSA 4
TTSB 4
TTSC ' vbCr was not in list so is still in the string
TTSD 9
TTSE 4
0 ' last separator honored
Corrected to:
Excluded = s.Split({vbCrLf, vbLf, vbCr}, _
StringSplitOptions.RemoveEmptyEntries)

List that this enumerator is bound to has been modified

I have this bit of code here, and at the next statement it's giving me an error saying:
List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.
I really don't know how to further explain this issue, but if you need me to I can try.
For Each itemChecked In storedAuthorsListbox.CheckedItems
Dim selectedAuthor As String = storedAuthorsListbox.SelectedItem.ToString()
Dim authorFile As String = "Authors\" & itemChecked.ToString()
Dim document As XmlReader = New XmlTextReader(authorFile)
metaInfo &= "[Author]" & vbNewLine
While (document.Read())
Dim type = document.NodeType
If (type = XmlNodeType.Element) Then
If (document.Name = "Name") Then
metaInfo &= "Name=" & document.ReadInnerXml.ToString() & vbNewLine
ElseIf (document.Name = "Website") Then
metaInfo &= "Website=" & document.ReadInnerXml.ToString() & vbNewLine
ElseIf (document.Name = "Notes") Then
metaInfo &= "Notes=" & document.ReadInnerXml.ToString() & vbNewLine
End If
End If
End While
document.Close()
Next
Some code somewhere is changing storedAuthorsListbox while you are iterating it. That code is not visible in the snippet. Do make sure that the posted code is not running in a worker thread, that is not legal. It certainly quacks like the kind of code you'd run in a worker.
The generic solution is to make a copy of the items and work from that copy instead of the control:
Dim copy = storedAuthorsListBox.SelectedItems.OfType(Of String)().ToList()
For Each itemchecked In copy
'' etc..
Next
If this runs in a worker thread then pass the copy to the worker.

VB.Net Regex Help

I've got 3 or 4 patterns that I'm comparing user input against and I need to figure out if the user input matches one of the patters and to return the match if it does.
Since the input is multiline, I'm passing each individual line like so:
Dim strRawInput() As String = Split(txtInput.Text, vbCrLf)
Dim strInput As String
txtOutput.Text = ""
For Each strInput In strRawInput
strInput.Trim(vbCr, vbLf, Chr(32))
Validation(strInput)
Next
Then I have this to find matches:
Dim m As Match
For i = 0 To strValidator.Length - 1
Dim r As New Regex(strValidator(i))
m = r.Match(strInput)
If m.Success Then
txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
Exit Sub
Else
End If
Next
txtOutput.Text = txtOutput.Text & "Not this time" & vbCrLf
How can I do this more efficiently? Also, I added the Exit Sub there to avoid showing the "Not this time" message even after a match is found (if the match is with one of the later patterns in the array), but I'd like to find a better way of doing that too.
Thanks in advance.
Rather than generating your Regexs in the loop, generate them one time at the startup of the application. So maybe something like:
Private Shared m_regexes As New List(Of Regex)
Shared Sub New()
For Each v As String In strValidator
m_regexes.Add(New Regex(v))
Next
End Sub
And then you can change your other code to:
For Each r As Regex In m_regexes
Dim m As Match = r.Match(strInput)
If m.Success Then
txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
Exit Sub
Else
End If
Next
Regarding the Exit Sub, I think it's fine, You've discovered that it matches at least one pattern, so why continue to evaluate the rest. But if you don't like methods that can "return" in multiple places, you could just replace it with a Boolean and a Exit For as:
Dim found as Boolean = false
For Each ...
If IsMatch Then
found = True
Exit For
End If
Next
If Found Then
....
Else
.....
End If
Hmm if that's the case then wouldn't this be even better?
For i = 0 To strValidator.Length - 1
Dim r As New Regex(strValidator(i))
Dim m As Match = r.Match(strInput)
If m.Success Then
txtOutput.Text = txtOutput.Text & "Success: " & m.ToString & vbCrLf
Exit Sub
End If
Next