Hassanation
Hassanation

Reputation: 886

parse Main Args[] string from windows context menu

I used the following code to implement the right clicked file that opened by my application. My aim is to get that file's path into my program.

I use:

public static string path = "";

static void Main(string[] args)
{
  if (args.Length > 0)
  {
     path = args[0];      
  }
}

Then I use the variable path, which is the file that opened by the application through the context menu.

Problem:

When the file name doesn't contain any spaces, the file path is imported without any problems. But when the file name contains any spaces, the file name shown without its extension besides it removes letters after the first space in the file name.

Example:

  1. fileName.pdffileName.pdf
  2. fileName blah blah.pdffilename

The second example shown that the file that contains spaces didn't imported as it should.

So, if there is any idea of how to parse the files that contains spaces without any problems with its name.

Upvotes: 1

Views: 676

Answers (2)

Hassanation
Hassanation

Reputation: 886

Some one posted a perfect answer, but he deleted it before i could upvote it and make it the right answer.

the answer was that i have to change the "%1" to "%0" and it worked.

Upvotes: 0

Justin
Justin

Reputation: 86729

This is because the operating system tries to split out the command line arguments for you, however can get it wrong if you don't put quotes in the right places. By default the following command line

MyConsoleApp.exe FileName blah blah.pdf

Will result in args containing the 3 strings FileName, blah and blah.pdf (split up by the spaces)

The most common solution to this problem is to surround the argument with quotes when invoking your application, for example

MyConsoleApp.exe "FileName blah blah.pdf"

This will result in args having length 1 with the first string having the value FileName blah blah.pdf (the OS strips out the extra quotes).

The alternative is to use the Environment.CommandLine property to obtain the full unparsed command line used to invoke your application, and to manually parse that string. This gives you more flexibility (as its not always possible to identify whether or not an argument was surrounded by quotes when using the args argument passed into Main), however is more effort - you should probably just make sure you use quotes when launching your application.

Upvotes: 3

Related Questions