Reputation: 863
I would like to pass some arguments to a little program i wrote. Its a program that expects 2 arguments. When i call it like this:
d:\littleProgram.exe d:\test\folder\ test.pdf
It works fine.
But when i try this:
d:\littleProgram.exe d:\test 2\folder\ test.pdf
It thinks is gets 3 arguments...
I tried quotes like this:
d:\littleProgram.exe "d:\test 2\folder\" test.pdf
No luck.
This is the vb code:
Module Module1
Sub Main(ByVal sArgs() As String)
If sArgs.Length = 0 Then
... some code
ElseIf sArgs.Length = 2 Then
... some code
End If
End Sub
End Module
Upvotes: 1
Views: 4990
Reputation: 27322
Command Line Arguments are Space Delimited.
If you need to pass an argument such as a filename that has (or may have) spaces you can enclose it in double quotes.
The exception to this is when arguments end with \
in which case you have to escape this with another \
So in your case this is what you need:
d:\littleProgram.exe "d:\test 2\folder\\" "test.pdf"
So your code would look like this:
For i As Integer = 0 To My.Application.CommandLineArgs.Count - 1
Debug.Writeline(My.Application.CommandLineArgs(i))
Next
Output:
d:\test 2\folder\
test.pdf
A simpler approach might be to remove the trailing slash and add the directory and filename together using Path.Combine
or just pass the fully qualified name as the argument (enclosed in double quotes)
Upvotes: 5
Reputation: 863
The problem was that when i use quotes arround first argument, i was actually escaping the closing qoute:
d:\littleProgram.exe "d:\test 2\folder\" test.pdf
This works fine now:
d:\littleProgram.exe "d:\test 2\folder" test.pdf
In combination with putting the \ inside the code of the program
Upvotes: 3
Reputation: 700372
The argument parsing har some strange rules for escaping characters, it's the \"
character combination in the arguments that causes the problem. This is a problem with the CommandLineToArgvW
method in Windows. See for example the article Commandline args ending in \" are subject to CommandLineToArgvW whackiness
Get the unparsed command line and parse it to get the parameters as expected:
Dim arguments As String() = _
Regex.Matches(Environment.CommandLine, "(?:""[^""]*""|[^ ]+)") _
.Cast(Of Match)().Select(Function(m) m.Value).Skip(1).ToArray()
Note: This parsing doesn't handle escape sequences as the original method, so you can't use for example ""
or \"
inside a quoted parameter to put a quotation mark in it. If you want to use the original method, you need to follow it's escaping rules and the arguments would have to be written as:
d:\littleProgram.exe "d:\test 2\folder\\" test.pdf
Upvotes: 0