Tutorial :Unable to fetch command line arguments properly in C#



Question:

In c#.Net I am not able to fetch the commandline argument properly. It has problems in case i give the command like:

myProgram.exe "c:\inputfolder\" "d:\output.txt"  

due to the backslash character(which i think acting as an escape character) in the args[] array i am getting only one argument instead of two It works fine if i gave without backslash:

myProgram.exe "c:\inputfolder" "d:\output.txt"  

or without double quotes:

myProgram.exe c:\inputfolder\ "d:\output.txt"  


Solution:1

I've never experienced such a problem but in case you like to parse the command line by your self use System.Environment.CommandLine to get it.


Solution:2

This is a well known parsing problem and there isn't a whole lot you can do about it besides get the whole command line as a single string and parse it yourself.


Solution:3

The backslash is escaping the quote character in the shell. You have to use an extra backslash:

myProgram.exe "c:\inputfolder\\" "d:\output.txt"  

You can use the following short sample program to test command line parsing:

using System;    class Program  {      static void Main(string[] args)      {          for (int i = 0; i < args.Length; i++)          {              Console.WriteLine(string.Format("Argument {0}: {1}", i, args[i]));          }      }  }  


Solution:4

In case someone else is trying to find official documentation on double-quotes in commandline args, the closest I could find was for c++ and it seems to directly apply: http://msdn.microsoft.com/en-us/library/17w5ykft.aspx


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »