1

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.

4

2 回答 2

3

这是因为操作系统会尝试为您拆分命令行参数,但是如果您没有将引号放在正确的位置,则可能会出错。默认情况下,以下命令行

MyConsoleApp.exe FileName blah blah.pdf

将导致args包含 3 个字符串FileNameblah并且blah.pdf(由空格分隔)

此问题最常见的解决方案是在调用应用程序时用引号将参数括起来,例如

MyConsoleApp.exe "FileName blah blah.pdf"

这将导致args长度为 1 且第一个字符串具有该值FileName blah blah.pdf(操作系统会去掉多余的引号)。

另一种方法是使用Environment.CommandLine 属性来获取用于调用应用程序的完整未解析命令行,并手动解析该字符串。这为您提供了更大的灵活性(因为在使用传递给 Main 的参数时,它并不总是可以识别参数是否被引号包围args),但是更加努力 - 您可能应该确保在启动应用程序时使用引号。

于 2012-10-15T12:24:28.593 回答
0

有人发布了一个完美的答案,但在我投赞成票并使其成为正确答案之前,他将其删除。

答案是我必须将“%1”更改为“%0”并且它有效。

于 2012-10-15T12:40:05.727 回答