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

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

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),"")

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

Split method with line breaker vb.net

I have a checkedlistbox to fill with the textbox values, but i have some issues cause if i paste the text from the textbox in a word file it comes with linebreakers, and not just spaces . Maybe that's why the checked list box is not being filled properly.
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Dim separated = TextBox2.Text.Split(vbNewLine & " ")
CheckedListBox1.Items.Clear()
CheckedListBox1.Items.AddRange(separated)
CheckedListBox1.Items.Remove(vbCrLf)
CheckedListBox1.Items.Remove("#")
CheckedListBox1.Items.Remove("PI")
End Sub
How can i get rid of this problem? If i paste the values in word they come like this:
You are currently separating the string where a space is followed by a new line. Any other spaces around this string are included in the output. You want to use a different version of Split, listing each character, so that ANY of those characters can be used to split the string:
Dim separated = TextBox2.Text.Split(vbCr, vbLf, vbTab, " "c)
This will treat one or more of space, tab, line feed OR carriage return as a split and will not include any of them in the strings it returns. It will however return a number of empty strings, so you will need to add the strings individually, filtering these out. The rest of the code can be replaced by this:
CheckedListBox1.Items.Clear()
For Each item In separated
If item <> "" Then CheckedListBox1.Items.Add(item)
Next
Get rid of all spaces and then split
Dim separated = TextBox2.Text.Replace(" ", "").Split(vbNewLine)
UPDATE to remove the tabs
char tabs = '\u0009';
Dim separated = TextBox2.Text.Replace(" ", "").Replace(tabs, "").Split(vbNewLine)
You need to remove all items that are not required prior to splitting.
SO... based on your example
char tabs = '\u0009';
StrippedText = TextBox2.Text.Replace(" ", "").Replace(tabs, "").Replace("P1" & vbCRLF & vbCRLF, "").Replace(vbCRLF & "#" & vbCRLF, "")
Dim separated = StrippedText.Split(vbNewLine)

Read file name for 5 to 10 digit account number, is this possible?

I am attempting to write a program in VB.net which will output some values in to a text file. Please be patient with me as I am very new to VB.net.
What I have so far is below:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim str As String
For Each File As String In System.IO.Directory.GetFiles(TextBox1.Text)
str = str & File & "|" & System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim & "|" & System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim & "||" & DateTimePicker1.Text & "|" & Environment.NewLine
Next
System.IO.File.WriteAllText("C:\output\output.txt", str)
End Sub
Results of output file (output.txt) when button3 is clicked are below:
C:\DirectoryTest\Clients\2356851-Kathy Winkler - Family Investments.pdf|2356851|2356851||04/10/2013|
C:\DirectoryTest\Clients\58736 -Katrina Armon - Sandlewood Homes Co.pdf|58736|58736||04/10/2013|
C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf|Karen Cooper|Karen Cooper||04/10/2013|
My code so far does exactly what I want it to do, the only thing is that I want to make the code smarter but don’t know how. Smarter as in is there a way I can make the below code only pick up the 5 to 10 digit account number seen in the filename, and if no account number exists in the file name to bring up a message box?
System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim & "|" & System.IO.Path.GetFileNameWithoutExtension(File).Split("-")(0).Trim
As you can see from the last line of the output…
C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf|Karen Cooper|Karen Cooper||04/10/2013|
…the customers name “Karen Cooper” is being displayed in both areas where the account number should be displayed. This is why I need to make this code smarter somehow have it search the file name for a 5 to 10 digit account number to display it after the file name as see in the other 2 examples.
Please let me know if this is possible. And do let me know if you have any questions.
Here is you some simple logic .... ofcouse you can just do something like finding the filename first but here you go
Dim returnval As String = ""
Dim s As String = "C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf|Karen Cooper|Karen Cooper||04/10/2013|"
For Each p As String In s
If IsNumeric(p) Then
returnval += p
Else
'MsgBox("no")
End If
Next
msgbox(returnval) will hold all your numbers 5-10 , depends on how specific you want to get from here
to break apart the filenames
'This will extract and return the filename from the specified path and filename.
'
Dim filePath As String = "c:\MyDirectory\MYFile.txt"
Dim slashPosition As Integer = filePath.LastIndexOf("\")
Dim filenameOnly As String = filePAth.Substring(slashPosition + 1)
MsgBox(filenameOnly)
*FOUND AT LINK http://www.vbforfree.com/274/extract-and-retrieve-the-filename-from-a-path/*
then manipulate your string from there as much as you want
You should give this a try. I haven't had a chance to test it but it should work
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim str As String
For Each File As String In System.IO.Directory.GetFiles(TextBox1.Text)
Dim strs as String() = System.IO.Path.GetFileNameWithoutExtension(File).Split("-")
Dim AccountNum as int = 0
For each section in strs()
' Loop through each section separated by - and try to cast it to an int
' you may want to use cLong instead
Try
AccountNum = cInt(section.trim())
exit for
Catch
End Try
Next
' DO LOGIC HERE TO BUILD OUTPUT with the account num now known
Next
System.IO.File.WriteAllText("C:\output\output.txt", str)
End Sub
How about yor file name ?
C:\DirectoryTest\Clients\Karen Cooper - 001548 - Famtime.pdf
Fairly, It should be
C:\DirectoryTest\Clients\001548 - Karen Cooper - Famtime.pdf
I would recommend using RegEx to extract the account number. A side benefit of using RegEx is that you can store the RegEx pattern outside of your code, such as in a configuration file, so if you ever need to modify the pattern, you could do so easily without recompiling your application.
Function GetAccountNumber(fileName As String) As String
Dim pattern As String = ".*?(?<acct>\d{5,10}).*?"
Dim regEx As New Regex(pattern)
Dim match As Match = regEx.Match(fileName)
Dim accountNumber As String = Nothing
If match.Success Then
Dim group As Group = match.Groups("acct")
If group.Success Then
accountNumber = group.Value
End If
End If
Return accountNumber
End Function
In the above example, I am using the following RegEx pattern to find the five to ten digit number in the string:
.*?(?<acct>\d{5,10}).*?
The .*? at the beginning and end of the pattern means any character, any number of times. The question mark means it's non-greedy. In other words, it only matches as many characters as necessary. By making it non-greedy, it will not steal-away any of the digits from the account number.
The parentheses surround the part of the string we are looking for (the account number). The ?<acct> at the beginning of the parenthetical group a name by which we can refer to it. In this case, I named the group acct. The \d means any digit character. The {5,10} means repeated between five and ten times.

Get only the line of text that contains the given word VB2010.net

I have a text file on my website and I download the whole string via webclient.downloadstring.
The text file contains this :
cookies,dishes,candy,(new line)
back,forward,refresh,(new line)
mail,media,mute,
This is just an example it's not the actual string , but it will do for help purposes.
What I want is I want to download the whole string , find the line that contains the word that was entered by the user in a textbox, get that line into a string, then I want to use the string.split with as delimiter the "," and output each word that is in the string into an richtextbox.
Now here is the code that I have used (some fields are removed for privacy reasons).
If TextBox1.TextLength > 0 Then
words = web.DownloadString("webadress here")
If words.Contains(TextBox1.Text) Then
'retrieval code here
Dim length As Integer = TextBox1.TextLength
Dim word As String
word = words.Substring(length + 1) // the plus 1 is for the ","
Dim cred() As String
cred = word.Split(",")
RichTextBox1.Text = "Your word: " + cred(0) + vbCr + "Your other word: " + cred(1)
Else
MsgBox("Sorry, but we could not find the word you have entered", MsgBoxStyle.Critical)
End If
Else
MsgBox("Please fill in an word", MsgBoxStyle.Critical)
End If
Now it works and no errors , but it only works for line 1 and not on line 2 or 3
what am I doing wrong ?
It's because the string words also contains the new line characters that you seem to be omitting in your code. You should first split words with the delimiter \n (or \r\n, depending on the platform), like this:
Dim lines() As String = words.Split("\n")
After that, you have an array of strings, each element representing a single line. Loop it through like this:
For Each line As String In lines
If line.Contains(TextBox1.Text) Then
'retrieval code here
End If
Next
Smi's answer is correct, but since you're using VB you need to split on vbNewLine. \n and \r are for use in C#. I get tripped up by that a lot.
Another way to do this is to use regular expressions. A regular expression match can both find the word you want and return the line that contains it in a single step.
Barely tested sample below. I couldn't quite figure out if your code was doing what you said it should be doing so I improvised based on your description.
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub ButtonFind_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFind.Click
Dim downloadedString As String
downloadedString = "cookies,dishes,candy," _
& vbNewLine & "back,forward,refresh," _
& vbNewLine & "mail,media,mute,"
'Use the regular expression anchor characters (^$) to match a line that contains the given text.
Dim wordToFind As String = TextBox1.Text & "," 'Include the comma that comes after each word to avoid partial matches.
Dim pattern As String = "^.*" & wordToFind & ".*$"
Dim rx As Regex = New Regex(pattern, RegexOptions.Multiline + RegexOptions.IgnoreCase)
Dim M As Match = rx.Match(downloadedString)
'M will either be Match.Empty (no matching word was found),
'or it will be the matching line.
If M IsNot Match.Empty Then
Dim words() As String = M.Value.Split(","c)
RichTextBox1.Clear()
For Each word As String In words
If Not String.IsNullOrEmpty(word) Then
RichTextBox1.AppendText(word & vbNewLine)
End If
Next
Else
RichTextBox1.Text = "No match found."
End If
End Sub
End Class