TextFieldParser Delimiters value not recognized correctly - vb.net

I have some simply problem i guess, if you see below statments work without the last one: ValueFromTextFile which its value comming from my text file. This value in text file is exactly the same: "vbTab" - however it looks like when i trying to get it from my text file its not recognized the same as first line {vbTab} from example. Why is that?
.Delimiters = New String() {vbTab} <- this works
.Delimiters = New String() {","} <- this works
.Delimiters = New String() {ValueFromTextFile} <- this doesn't work
EDIT: (helper delimeter class):
Public Class CharDelimeterHelper
Private _delimeter As String
Public Sub New(ByVal delimeter As String)
Me._delimeter = delimeter
End Sub
Function GetDelimeterFormat() As ??
Dim result As ??
Select Case _delimeter
Case "vbTab"
result = ControlChars.Tab
Case ","
result = ","
Case Else
End Select
Return result
End Function
End Class

The string "vbTab" is not the same as the constant vbTab.
So if ValueFromTextFile equals "vbTab" is only works if all fields are separated by the string "vbTab" which i strongly doubt. I guess that they are separated by the tab-character which is represented by the vbTab-constant. You could also use ControlChars.Tab.

Related

Get a specific value from the line in brackets (Visual Studio 2019)

I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function

Identify first letter from every word in a TextBox

I tried to create a unique code for each shop in the form I made. I have two TextBox controls (TBNameStore and TBCodeStore). What I want is that when I write the name of the shop, for example "Brothers in Arm", in TBNameStore, then TBCodeStore should automatically be filled with the text "BIA".
How can I do that?
Well I write a code that can help you with your problem.
Option Strict On
Public Class Form1
Public Function GetInitials(ByVal MyText As String) As String
Dim Initials As String = ""
Dim AllWords() As String = MyText.Split(" "c)
For Each Word As String In AllWords
If Word.Length > 0 Then
Initials = Initials & Word.Chars(0).ToString.ToUpper
End If
Next
Return Initials
End Function
Private Sub TBNameStore_TextChanged(sender As Object, e As EventArgs) Handles TBNameStore.TextChanged
TBCodeStore.Text = GetInitials(TBNameStore.Text)
End Sub
End Class
Like you can see, the GetInitials get you all the first letter of all the words in the text.
One possible solution using the mentioned Split and SubString methods and LINQ could look like this:
create a StringBuilder where every first character of each word is stored
separate the words using the specified delimiter (default is empty space) using the String.Split method
convert the array to list in order to apply the LINQ-ToList extension => ToList()
for each found word => ForEach(sub (word as String) ...
take the first character from the word, convert it to upper case and put it in the result
=> result.Append(word.SubString(0, 1).ToUpper())
return the result as string => result.ToString()
The code looks like this:
private function abbreviation(input as String, optional delimiter as String = " ")
dim result = new StringBuilder()
input.Split(delimiter) _
.ToList() _
.ForEach(sub (word as String)
result.Append(word.SubString(0, 1).ToUpper())
end sub)
return result.ToString()
end function
Usage:
dim s = "Brothers in Arms"
Console.WriteLine("{0} => {1}", s, abbreviation(s))
and the output looks like expected:
Brothers in Arms => BIA

Splitting string by two conditions in vb.net 2014

I'm trying to split a string into a list of strings with this vb.net code, while adding it to a dictionary of String:
objevt.wbStr.Add(b, objevt.metalbelowwidth.Item(b).Split({",","-"}).ToList)
But I get an error saying "Value of '1-dimentitional arrary of string' cannot be converted to 'Char' "
If I try to implement splitting with just the comma, it works fine. So the following code works.
objevt.wbStr.Add(b, objevt.metalbelowwidth.Item(b).Split(",").ToList)
But I really want to split the string with two conditions. Any help is appreciated. Thanks!
One of the overloads of the Split Method that takes a String array also needs to have a StringSplitOption parameter also set.
objevt.wbStr.Add(b, objevt.metalbelowwidth.Item(b).Split(New String() {",", "-"}, StringSplitOptions.None).ToList)
Sub Main()
Dim myString As String = "H,c,J-Hello-World"
Dim myList As List(Of String) = New List(Of String)
myList = myString.Split(New String() {"-", ","}, StringSplitOptions.None).ToList
For Each s As String In myList
Console.WriteLine(s)
Next
Console.ReadLine()
End Sub
You need to use the overloaded Split method with an array of char as the separators, like so:
objevt.metalbelowwidth.Item(b).Split(New [Char]() {","c, "-"c })
Demo here

How to remove letters?

i just wanna ask:
i have a label40.text
with a content of {a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}
and i also have have a label39.text that will change its output everytime a certain changes happens.
My question is
How can i embed this simulation through a code?
If Label39.text = "a" then the content of label40.text "a" will be remove and the list of alphabets will be remain alphabetically.
I want that also to be happen anytime my label39.text will change its value "RANDOMLY"
Example if label39.text = "a,b,c,d,x,z" then
label40.text = "e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y"
this is my code so far
Dim patterns As String
patterns = Label39.Text
Dim tobefollow As String
tobefollow = Label40.Text
Dim matches As MatchCollection = Regex.Matches(patterns, tobefollow)
If Regex.IsMatch(patterns, tobefollow) Then
'this where i will put my code to make my example
End If
First of all, note that you are populating the patterns and tobefollow variables wrongly (you were doing it right in the other question); it should be:
patterns = Label40.Text
tobefollow = Label39.Text
Also bear in mind that what you want can easily be accomplished without relying on Regex; for example via:
If (Label40.Text.ToLower().Contains(Label39.Text.ToLower())) Then
'this where i will put my code to make my example
End If
Regarding what you want this time, you can rely on .Replace: .Replace("text to be deleted", "") will remove this letter; but you have also to account for the commas. Code to be put inside the condition:
Dim origString As String = Label40.Text
Label40.Text = Label40.Text.ToLower().Replace(Label39.Text.ToLower() & ",", "")
If (origString = Label40.Text) Then
'It means that it does not have any comma, that is, refers to the last letter
Label40.Text = Label40.Text.ToLower().Replace("," & Label39.Text.ToLower(), "")
End If
An alternate answer would to use the String.Split and the String.Join Methods to breakdown your strings into individual characters then remove them from the List and join them back together. Here is a Function that does that:
Private Function RemoveLetters(str1 As String, str2 As String) As String
Dim sep() As String = {","}
Dim list1 As List(Of String) = str1.Split(sep, StringSplitOptions.None).ToList
Dim list2 As List(Of String) = str2.Split(sep, StringSplitOptions.None).ToList
For Each s As String In list2
list1.Remove(s)
Next
Return String.Join(",", list1)
End Function
you would use it like this:
Label40.Text = RemoveLetters(Label40.Text, Label39.Text)

Converting Fixed length statement from VB6 to VB.Net

We perform a protocol based data sending to device where the device requires a formatted data packets.
the sample packet data is XXFSXXXFSXXXXXXXFSXXXXXX. The X mentioned is the max length size of each string. if data is less than string max length it should be filled with NULL character like ..11FS123FS1234XXXX (the remaining X will be filled with NULL).
I am just trying to convert one of VB6 function to VB.Net and below is the converted statement where i am facing issue
Option Strict Off
Option Explicit On
Imports Microsoft.VisualBasic.Compatibility.VB6
Imports System
Imports System.Runtime.InteropServices
Module FunctionCmd_Msg
Public FunCommand_Msg As Fun_CommandMessage = Fun_CommandMessage.CreateInstance()
'Function Command Message
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _ _
Public Structure Fun_CommandMessage
<VBFixedString(1)> Public one As String
<VBFixedString(1)> Public two As String
<VBFixedString(3)> Public three As String
Dim five As String
<VBFixedString(8)> Public four As String
Public Shared Function CreateInstance() As Fun_CommandMessage
Dim result As New Fun_CommandMessage
result.one = String.Empty
result.two = String.Empty
result.three = String.Empty
result.four = String.Empty
result.five = String.Empty
End Function
End Structure
End Module
assuming:
one = "1"
two = "1"
three = "123"
four = "5678"
five = "testing"
FS = character (field separator)
on concatenating the strings i need a fixed length string such like this:
one & two & FS & three & FS & five & FS & four
output: since four is a fixed length string of 8 length remaining 4 characters should be filled with null as below
11 FS 123 FS testing FS 5678XXXX
Fixed-length strings simply make no sense in .NET any more. Microsoft tried to provide a similar class for easier upgrade but the truth is that you should change your code depending on usage:
What did the fixed-length string do in your VB6 code? Was it for no good reason? Then use a normal String in .NET.
Was it for interop with a C API? Then use marshalling to set a size for an array in the C API call.
Just forget about the fixed length, and use regular vb.net strings. They will return fine to whatever calls that code, including interop.
So, just pad your strings, and you off to the races.
In fact, build a Msg class that does the dirty work for you.
This looks quite nice to me:
NOTE how I set this up that you ONLY define the length of the string in ONE place. (so I use len(m_string) to determine the length from THEN on in the code.
Also, for debug and this example, in place of vbcharNull (which you should use), I used X for testing.
Now, in your code?
Just use this:
Dim Msg As New MyMsg
With Msg
.one = "A"
.two = "B"
.three = "C"
.four = "D"
.Five = "E"
End With
Debug.WriteLine(Msg.Msg("*") & vbCrLf)
Debug.WriteLine("total lenght = " & Len(Msg.Msg("X").ToString))
Output:
A*B*CXX*EXXXXXXX*DXXXXXXX
total lenght = 25
I note in your code that you have FIVE before FOUR - but if that is what you want, then no problem
Note that the class ALWAYS maintains the lengths for you.
So just paste this code into your module or even a new separate class.
Public Class MyMsg
'Dim cPad As Char = vbNullChar
Dim cPad As Char = "X"
Private m_one As String = New String(cPad, 1)
Private m_two As String = New String(cPad, 1)
Private m_three As String = New String(cPad, 3)
Private m_four As String = New String(cPad, 8)
Private m_five As String = New String(cPad, 8)
Public Property one As String
Get
Return m_one
End Get
Set(value As String)
m_one = MyPad(value, m_one)
End Set
End Property
Public Property two As String
Get
Return m_two
End Get
Set(value As String)
m_two = MyPad(value, m_two)
End Set
End Property
Public Property three As String
Get
Return m_three
End Get
Set(value As String)
m_three = MyPad(value, m_three)
End Set
End Property
Public Property four As String
Get
Return m_four
End Get
Set(value As String)
m_four = MyPad(value, m_four)
End Set
End Property
Public Property Five As String
Get
Return m_five
End Get
Set(value As String)
m_five = MyPad(value, m_five)
End Set
End Property
Public Function Msg(FS As String) As String
Return m_one & FS & m_two & FS & m_three & FS & m_five & FS & m_four
End Function
Private Function MyPad(str As String, strV As String) As String
Return Strings.Left(str & New String(Me.cPad, Len(strV)), Len(strV))
End Function
End Class
As noted, change the commented out line of "X" for the char back to vbCharNull.
And of course you STILL get to choose the delimiter. I used
Msg.Msg("*")
so I used a "*", but you can use space, or anything you want.