Visual Basic Command Line [duplicate] - vb.net

Is it possible to return the arguments from the processPath in this example?
This might make more sense, sorry.
Dim processName As String
Dim processPath As String
If processName = "cmd" Then
Dim arguments As String() = Environment.GetCommandLineArgs()
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments))
End If

A simple (and clean) way to accomplish this would be to just modify your Sub Main as follows,
Sub Main(args As String())
' CMD Arguments are contained in the args variable
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", args))
End Sub

The VB.Net solution to your problem is to use Command() VB.Net function when you search to display command's line of currently executed process.
Sub Main(args As String())
Dim sCmdLine As String = Environment.CommandLine()
Console.WriteLine("CommandLine: " & sCmdLine)
Dim iPos = sCmdLine.IndexOf("""", 2)
Dim sCmdLineArgs = sCmdLine.Substring(iPos + 1).Trim()
Console.WriteLine("CommandLine.Arguments: " & sCmdLineArgs)
End Sub
The first outpout will display the complete command's line with name of program.
The second output will display only the command's line without program's name.
Using args is C/C++/C#/Java technic.
Using CommandLine() function is pure VB and is more intuitive because is return command's line as typed by user without supposing that arguments are type without blank.
Example:
LIST-LINE 1-12, WHERE=(20-24='TYPES'),to-area=4
LIST-LINE 1 - 12, WHERE = ( 20-24 = 'TYPES' ) , to-area = 4
In this command's syntax, arguments are separated by COMMA and not by spaces.
In this case, it is better to not use args technic that is more linked to C and Unix where command syntax accepts arguments separated by space !

Another option
Sub WhatEver()
Dim strArg() as string
strArg = Command().Split(" ")
' strArg(0) is first argument and so on
'
'
End Sub

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

Count words in an external file using delimiter of a space

I want to calculate the number of words in a text file using a delimiter of a space (" "), however I am struggling.
Dim counter = 0
Dim delim = " "
Dim fields() As String
fields = Nothing
Dim line As String
line = Input
While (SR.EndOfStream)
line = SR.ReadLine()
End While
Console.WriteLine(vbLf & "Reading File.. ")
fields = line.Split(delim.ToCharArray())
For i = 0 To fields.Length
counter = counter + 1
Next
SR.Close()
Console.WriteLine(vbLf & "The word count is {0}", counter)
I do not know how to open the file and to get the do this, very confused; would like an explanation so I can edit and understand from it.
You're going to be reading a file as the source of the data, so let's create a variable to refer to its filename:
Dim srcFile = "C:\temp\twolines.txt"
As you have shown already, a variable is needed to hold the number of words found:
Dim counter = 0
To read from the file, a StreamReader will do the job. Now, we look at the documenation for it (yes, really) and notice that it has a Dispose method. That means that we have to explicitly dispose of it after we've used it to make sure that no system resources are tied up until the computer is next rebooted (e.g there could be a "memory leak"). Fortunately, there is the Using construct to take care of that for us:
Using sr As New StreamReader(srcFile)
And now we want to iterate over the content of the file line-by-line until the end of the file:
While Not sr.EndOfStream
Then we want to read a line and find how many items separated by spaces it has:
counter += sr.ReadLine().Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Length
The += operator is like saying "add n to a" instead of saying "a = a + n". The {" "c} is a literal array of the character " "c. The c tells it that is a character and not a string of one character. The StringSplitOptions.RemoveEmptyEntries means that if there was text of "one two" then it would ignore the extra spaces.
So, if you were writing a console program, it might look like:
Imports System.IO
Module Module1
Sub Main()
Dim srcFile = "C:\temp\twolines.txt"
Dim counter = 0
Using sr As New StreamReader(srcFile)
While Not sr.EndOfStream
counter += sr.ReadLine().Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Length
End While
End Using
Console.WriteLine(counter)
Console.ReadLine()
End Sub
End Module
Any embellishments such as writing out what the number represents or error checking are left up to you.
With Path.Combine you don't have to worry about where the slashes or back slashes go. You can get the path of special folders easily using the Environment class. The File class of System.IO is shared so you don't have to create an instance.
Public Sub Main()
Dim p As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Chapters.txt")
Debug.Print(Environment.SpecialFolder.MyDocuments.ToString)
Dim count As Integer = GetCount(p)
Console.WriteLine(count)
Console.ReadKey()
End Sub
Private Function GetCount(Path As String) As Integer
Dim s = File.ReadAllText(Path)
Return s.Split().Length
End Function
Use Split function, then Directly get the length of result array and add 1 to it.

Replacing character in a text file with comma delimited

I have a comma delimited file with sample values :
1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT
Question : how to replace the comma in the last column which is "AAA,TEXT"
The result should be this way:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
There is an overload of String.Split which takes an argument telling it the maximum number of parts to return. You could use it like this:
Option Infer On
Option Strict On
Module Module1
'TODO: think up a good name for this function
Function X(s As String) As String
Dim nReturnParts = 7
Dim parts = s.Split({","c}, nReturnParts)
If parts.Count < nReturnParts Then
Throw New ArgumentException($"Not enough parts - needs {nReturnParts}.")
End If
parts(nReturnParts - 1) = parts(nReturnParts - 1).Replace(",", "")
Return String.Join(",", parts)
End Function
Sub Main()
Dim s() = {"1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT",
"1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT",
"1,1076103,22-NOV-16,21051169,50,1083,C,C,C,TEXT"}
For Each a In s
Console.WriteLine(X(a))
Next
Console.ReadLine()
End Sub
End Module
Outputs:
1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT
1,1076103,22-NOV-16,21051169,50,1083,CCCTEXT
Is simple, but learn a bit how to use string ;)
Public Function MDP(strWork As String)
Dim splitted() As String = strWork.Split(","c)
Dim firsts As New List(Of String)
For i As Integer = 0 To splitted.Count - 3
firsts.Add(splitted(i))
Next
Dim result As String = System.String.Join(",", firsts)
Return result & "," & splitted(splitted.Count - 2) & splitted(splitted.Count - 1)
End Function
Then call with:
Dim finished As String = MDP("1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT")

Get the arguments from a command line in vb.net

Is it possible to return the arguments from the processPath in this example?
This might make more sense, sorry.
Dim processName As String
Dim processPath As String
If processName = "cmd" Then
Dim arguments As String() = Environment.GetCommandLineArgs()
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments))
End If
A simple (and clean) way to accomplish this would be to just modify your Sub Main as follows,
Sub Main(args As String())
' CMD Arguments are contained in the args variable
Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", args))
End Sub
The VB.Net solution to your problem is to use Command() VB.Net function when you search to display command's line of currently executed process.
Sub Main(args As String())
Dim sCmdLine As String = Environment.CommandLine()
Console.WriteLine("CommandLine: " & sCmdLine)
Dim iPos = sCmdLine.IndexOf("""", 2)
Dim sCmdLineArgs = sCmdLine.Substring(iPos + 1).Trim()
Console.WriteLine("CommandLine.Arguments: " & sCmdLineArgs)
End Sub
The first outpout will display the complete command's line with name of program.
The second output will display only the command's line without program's name.
Using args is C/C++/C#/Java technic.
Using CommandLine() function is pure VB and is more intuitive because is return command's line as typed by user without supposing that arguments are type without blank.
Example:
LIST-LINE 1-12, WHERE=(20-24='TYPES'),to-area=4
LIST-LINE 1 - 12, WHERE = ( 20-24 = 'TYPES' ) , to-area = 4
In this command's syntax, arguments are separated by COMMA and not by spaces.
In this case, it is better to not use args technic that is more linked to C and Unix where command syntax accepts arguments separated by space !
Another option
Sub WhatEver()
Dim strArg() as string
strArg = Command().Split(" ")
' strArg(0) is first argument and so on
'
'
End Sub

.split removes tabs/spaces in string?

i am trying to split a string up into separate lines with the following code, but for some reason it is also removing the spaces in the string.
Dim calculationText As String
calculationText = File.ReadAllText(fileName)
Dim fields() As String
fields = calculationText.Split(vbCrLf)
when i am in debugger mode, i look at fields, and every element has a line of the string but all the spaces and tabs are removed.
any reason for this?
If you are reading from a file, can you use:
Sub Main()
Dim fields As New List(Of String)
' read file into list
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(filename)
Try
Do While sr.Peek() >= 0
fields.Add(sr.ReadLine())
Loop
Finally
If sr IsNot Nothing Then sr.Close()
End Try
End Using
' check results
For Each line As String In fields
Console.WriteLine(line)
Next
End Sub
How 'bout:
Dim fields() As String = File.ReadAllLines(fileName)
As for why string.Split() is doing weird things...
vbCrLf is a string, and there's not an overload for string.split that accepts a single string parameter. If he were to turn on Option Explicit it wouldn't even compile, but since it's off, vbCrLf can be interpreted as an array of characters. And in this code, that's exactly what happens:
Sub Main()
Dim z As String = "The quick brown" & vbCrLf & " fox jumps over the lazy dogs."
Dim a() As String = z.Split(vbCrLf)
For Each c As String In a
Console.WriteLine(c)
Next
Console.ReadKey(True)
End Sub
You'll see two line breaks between the 1st and 2nd parts of that string. Something else is stripping out the spaces. Can you share the larger code block?
Gotta say I've never seen it do that, and I've used String.Split extensively. Are they really really gone, or is it a trick of the debugger?
There's not actually any .Split method that takes one string as the parameter, so the VB compiler would be doing "things" behind the scenes to pick a different overload. To try and force the correct overload, you could try calculationText.Split(vbCrLf.ToCharArray()). I doubt it will help, but you never know :-)