Passing command-line arguments in C#

I'm trying to pass command-line arguments to a C# application, but I have problem passing something like this

"C:\Documents and Settings\All Users\Start Menu\Programs\App name"

even if I add " " to the argument.

Here is my code:

    public ObjectModel(String[] args)
    {
        if (args.Length == 0) return; //no command line arg.
        //System.Windows.Forms.MessageBox.Show(args.Length.ToString());
        //System.Windows.Forms.MessageBox.Show(args[0]);
        //System.Windows.Forms.MessageBox.Show(args[1]);
        //System.Windows.Forms.MessageBox.Show(args[2]);
        //System.Windows.Forms.MessageBox.Show(args[3]);
        if (args.Length == 3)
        {
            try
            {
                RemoveInstalledFolder(args[0]);
                RemoveUserAccount(args[1]);
                RemoveShortCutFolder(args[2]);
                RemoveRegistryEntry();
            }
            catch (Exception e)
            {
            }
        }
        }

And here is what I'm passing:

C:\WINDOWS\Uninstaller.exe  "C:\Program Files\Application name\"  "username"  "C:\Documents and Settings\All Users\Start Menu\Programs\application name"

The problem is I can get the first and the second args correctly, but the last one it gets as C:\Documents.

Any help?


Solution 1:

I just ran a check and verified the problem. It surprised me, but it is the last \ in the first argument.

"C:\Program Files\Application name\" <== remove the last '\'

This needs more explanation, does anybody have an idea? I'm inclined to call it a bug.


Part 2, I ran a few more tests and

"X:\\aa aa\\" "X:\\aa aa\" next

becomes

X:\\aa aa\
X:\\aa aa" next

A little Google action gives some insight from a blog by Jon Galloway, the basic rules are:

  • the backslash is the escape character
  • always escape quotes
  • only escape backslashes when they precede a quote.

Solution 2:

To add Ian Kemp's answer

If you assembly is called "myProg.exe" and you pass in the string "C:\Documents and Settings\All Users\Start Menu\Programs\App name" link so

C:\>myprog.exe "C:\Documents and Settings\All Users\Start Menu\Programs\App name"

the string "C:\Documents and Settings\All Users\Start Menu\Programs\App name"

will be at args[0].

Solution 3:

To add to what everyone else has already said, It might be an escaping problem. You should escape your backslashes by another backslash.

Should be something like:

C:\>myprog.exe "C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\App name"