Console app not parsing correctly args with white spaces - c#

I've created a .NET console application that gets some command line arguments.
When I pass args with white spaces, I use quotes to embrace these arguments so that they are not splitted by cmd:
C:\MyAppDir> MyApp argument1 "argument 2" "the third argument"
If I execute the app in Windows XP it works fine: it gets 3 arguments:
argument1
argument 2
the third argument
However, if i execute it in Windows Server 2008 it seems to ignore quotes: it gets 6 arguments:
argument1
"argument
2"
"the
third
argument"
Any ideas why?
NOTE: I printed arguments just when Main starts execution using this code:
Console.WriteLine("Command line arguments:");
foreach (string arg in args)
{
Console.WriteLine("# " + arg);
}

Make sure the character you are typing is indeed the double quote ".
Maybe it's a character that looks like it.
I know my Greek language settings produce a " but it's not read that way.

Please Try it.
C:\MyAppDir> MyApp argument1 \"argument 2\" \"the third argument\"

You can try, put each arguments between Quota"" and in the paths put double backslash for example like that:
generadorPlantillasPDF.exe "C:\GDI\desarrollos\celula canales\proyectos\Progreso\curso xml\" generadorprogreso.xml C:\Temp\ BVI "C:\GDI\desarrollos\celula canales\proyectos\Progreso\plantilla\" "C:\GDI\desarrollos\celula canales\proyectos\Progreso\" "Formulario Progreso Version 2.0.docx" C:\Temp\

Related

C# ProcessStartInfo: Second process receives no arguments

I'm trying to make a call from one process to start another, supplying starting arguments as separate parameters in a ProcessStartInfo. The starting call uses a URL registered in Windows to find the second program, entered into FileName. I then add a string containing 4 parameters to Arguments. As I have understood it, the spaces in the string indicate the separation of the arguments.
Program 1
//Create starting information
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo() {
FileName = "urlHandle:",
Arguments = "/argA valueA /argB valueB"
};
//Start second program
System.Diagnostics.Process.Start(startInfo);
Program 2
//Print received arguments to a file
Environment.GetCommandLineArgs().ToList().ForEach(a => writer.WriteLine(a + ",\t"));
The second program starts as intended (meaning the URL is working), but the output is incomplete.
[path to .exe of second program],
urlHandle:,
It contains the path to the program, the string set as FileName , but everything put into Arguments is missing.
Does anybody have any ideas why the arguments disappear?
Note 1: If I would add the arguments into the FileName, I would receive them as one string. In order to trigger the behaviour I want in the second program, I must supply it with several parameters instead of one. I know this is possible from testing it manually from the terminal.
Note 2: I'm using .Net Framework, so trying ArgumentList from .Net Core is not an option.
After some more tests I have found the issue. The error does not lie in how I set up and use ProcessStartInfo, but rather in that I am using a custom URL protocol.
In the Windows registry one defines the number of parameters that can be sent via the URL call ("C:\[path to my .exe]" "%1"). The first argument is the Filename, and is as such the only thing sent via the protocol. In order to send more, one is required to add "%2", "%3", etc.
Note: The path itself becomes argument 0 in the receiving program, while the actual sent parameters start at argument 1 and beyond.

Let the shell parse or do your own parsing (powershell/cmd)

I develop an application with command line parameters and use it in cmd shell and powershell. There it is obvious that the arguments are received differently in main() of my application.
static void Main(string[] args)
{
// In cmd shell: args[0] == "-ipaddress=127.0.0.1"
// In powershell: args[0] == "-ipaddress=127"
// and args[1] == ".0.0.1"
}
Example:
myApp.exe -ipaddress=127.0.0.1
In my C# application the arguments are interpreted differently depending on the shell I start the app in.
In cmd shell: arg[0]=-ipaddress=127.0.0.1
In powershell: arg[0]=-ipaddress=127 and arg[1]=.0.0.1
What is best practice here?
Should I join all args[] and parse the arguments in my application?
Should I rely on the shell's parser?
I would abandon cmd shell support completely and just created proper PowerShell cmdlet. Writing a Windows PowerShell Cmdlet. But I don't know your exact requirements.
In general calling executable from cmd and PowerShell should work same way. For example line, "> ping -n 3 google.com" just works fine no matter where you put it.
tl;dr:
When calling from PowerShell, enclose the entire argument in '...' (single quotes) to ensure that it is passed as-is:
myApp.exe '-ipaddress=127.0.0.1'
You've run into a parsing bug[1]
where PowerShell breaks an unquoted argument that starts with - in two at the first .
The following simplified example demonstrates that:
# Helper function that echoes all arguments.
function Out-Argument { $i = 0; $Args | % { 'arg[{0}]: {1}' -f ($i++), $_ }}
# Pass an unquoted argument that starts with "-" and has an embedded "."
Out-Argument -foo=bar.baz
The above yields:
arg[0]: -foo=bar
arg[1]: .baz
[1] The presumptive bug is present as of Windows PowerShell v5.1 / PowerShell Core v6.0.1 and has been reported on GitHub.
A PSv2 variation of the bug affects . when enclosed in "..." in the interior of the argument - see this answer of mine.

Displaying command in cmd console

I'm trying to run a command in cmd using C# and am having some difficulties. I'd like to be able to write the command to the cmd console so I can see what it's trying to run (I think there's some issue with the quotes or something, so if I could see the actual string in the command line, I'd be able to see exactly what the problem is). My code looks like this:
var processStartInfo = new ProcessStartInfo("cmd", "/c"+commandString);
processStartInfo.CreateNoWindow = true;
Process.Start(processStartInfo);
So basically, I just want to see the string commandString written in the console. Any help would be greatly greatly appreciated.
string CommandLineString = #"""C:\Program Files\Microsoft SQL Server\100\Tools\Binn\bcp.exe"" ""SELECT * FROM table where date >= '2009-01-01'"" queryout ""C:\Data\data.dat"" -S DBSW0323 -d CMS -n -T";
In this case, the problem is probably just your lack of a space after "/c".
var processStartInfo = new ProcessStartInfo("cmd", "/c " + commandString);
As for viewing in a command window, instead, you will probably be better off inspecting the Arguments property of your processStartInfo instance.
EDIT
Taking into account the command line details you posted, I believe this is what your issue is. Check out the following from cmd help:
If /C or /K is specified, then the remainder of the command line after
the switch is processed as a command line, where the following logic is
used to process quote (") characters:
If all of the following conditions are met, then quote characters
on the command line are preserved:
no /S switch
exactly two quote characters
no special characters between the two quote characters,
where special is one of: &<>()#^|
there are one or more whitespace characters between the
the two quote characters
the string between the two quote characters is the name
of an executable file.
Since you are using /c, you have quote and special char issues still. Try wrapping your entire commandString in a set of quotes.
Take this simple example for instance (creating temp.txt manually of course):
string commandString = #"""C:\WINDOWS\Notepad.exe"" ""C:\temp.txt""";
var processStartInfo = new ProcessStartInfo("cmd", "/c " + commandString);
The command line to be executed will be: /c "C:\WINDOWS\Notepad.exe" "C:\temp.txt", but this will fail since "C:\temp.txt" is not an executable.
If you wrap the whole thing in one last set of quotes, you should see the intended result:
string commandString = #"""""C:\WINDOWS\Notepad.exe"" ""C:\temp.txt""""";
var processStartInfo = new ProcessStartInfo("cmd", "/c " + commandString);
Resulting in a command line of: /c ""C:\WINDOWS\Notepad.exe" "C:\temp.txt"" and ultimately opening notepad with your test file.
That string is not "written" to the console, it's part of the argument list for a program you launch (which in this case happens to be cmd.exe). Since the console created is owned by that program, unless it wants to print its arguments for its own reasons (which it won't) this is not directly doable.
If you simply want to debug then why not inspect the value of commandString, or write it out into a log file?
If you absolutely need the command line to be displayed in the console then you could resort to hacks (run another intermediate program that prints the command line and then calls cmd.exe with it), but unless there is some other good reason to use this approach I would not recommend it.

StartInfo.Arguments in c#

I found the following snippet of the code:
using System;
using System.Diagnostics;
public class RedirectingProcessOutput
{
public static void Main()
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c dir *.cs";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);
}
}
but I can't figure out what this p.StartInfo.Arguments = "/c dir *.cs"; is doing? thanks in advance for any explanation
It's passing command line arguments to the process that will be launched.
In this particular case, the process is the Windows shell (cmd.exe). Passing a command line to it will cause it to execute this command when started; then, because of the /c parameter at the beginning it will terminate itself.
So the output of the process will be exactly what you will get if you open a command prompt and enter the command dir *.cs.
In the beginning was exec(3) and its friends, which accept the path to an executable and a variable length list of pointers to arguments. In sane operating systems, The process that gets started receives a point to the argument list, each word of which contains a pointer to and individual string. Sane shells parse the command line and populate the argument list required by exec(3).
You can see a direct correlation between the argument list accepted by exec(3):
exec ("some.executable.file", "arg1" , "arg2" , "arg3" , ... ) ;
and what gets passed to the entrypoint of the process:
int main ( char *arg[] ) { ... }
where argv[0] is the executable name, and argv[1]—argv[n-2] are the individual arguments, and argv[n-1] is a NULL pointer to indicate the end of the argument list.
Both conceptually simple and simple to implement.
CP/M didn't do it that way (I assume because of limited memory). It passed the started process the address of the raw command line from the shell and left its parsing up the process.
DOS followed in 1982 as clone of CP/M, handing a started process the address of the raw command line as well.
Windows hasn't deviated from that model since its inception. The Win32 CreateProcess() function
BOOL WINAPI CreateProcess(
__in_opt LPCTSTR lpApplicationName,
__inout_opt LPTSTR lpCommandLine,
...
);
still does the same thing, passing the raw command line to be passed to the program. The C runtime library, of course, takes care of the command line parsing for you...more or less.
So...in the CLR/.Net world, because of all this history, and because the CLR was designed to be dependent on the Win32 APIs, you have pass a complete command line to the process to be started. Why they didn't let you pass a params string[], instead and have the CLR build the command line is something that Microsoft's developers kept close to their chest.
Building the command line required by the started program is simple. You just join each argument into a single string with an SP character separating the arguments. Easy!
...until one of your arguments contains whitespace or a double quote character (").
Then you have to quote one or all of the arguments. Should be easy, but due to the bizarre quote rules, there are a lot of edge conditions that can trip you up.
A Windows command-line is broken up into words separated by whitespace, optionally quoted with double-quoted ("). Partly because Windows also got the path separater wrong (\ rather than /), the quoting rules are...byzantine. If you dig into the Windows CRT source code (the file is something like {VisualStudioInstallLocation}\VC\crt\src\stdargv.c), you'll find the command line parsing code.
That line just gives an argument to that proccess.

.NET command line argument bug?

I am trying to read command lien argument but it seems there is some kind of bug in .NET.
The parameter which I pass to my console application
/i "C:\Projects\PC\trunk\Simulator\PDF-Source\PDF-Source\bin\Debug\ConversionFiles\dummy.pdf" /o "result"
CommandLine variable return three arguments, but I pass four and values of these arguments messed up.
/i = true
"C:\Projects\PC\trunk\Simulator\PDF-Source\PDF-Source\bin\Debug\ConversionFiles\dummy.pdf" = true
/o = "result"
As you see only the last argument is parsed corectlly. Is this bug?
regards,
Tomas
My code
static void Main(string[] args)
{
Arguments CommandLine = new Arguments(args);
It looks like the problem is in the Arguments class. I bet if you check out args array you will find 4 elements there.

Categories

Resources