c# - Process.Start() 启动的应用程序未获取参数

标签 c# process.start processstartinfo

使用 C#,我尝试使用 Process.Start() 将命令行参数传递给新进程:

string path = @"C:\Demo\Demo.exe";
string arguments = "one two three";
ProcessStartInfo startInfo = new ProcessStartInfo
   {
      FileName = path,
      Arguments = arguments
   };
var process = Process.Start(startInfo);

我的 C 应用程序 Demo.exe 只是回显命令行参数:

int main( int argc, char *argv[] )
{
   int count=0;

   // Display each command-line argument.
    printf( "\nCommand-line arguments:\n" );
    for( count = 0; count < argc; count++ )
        printf( "  argv[%d]   %s\n", count, argv[count] );

    while(1);
}

如果我从 cmd.exe 启动我的应用程序,我会得到合理的输出:

Command-line arguments:
 argv[0]   Demo.exe
 argv[1]   one
 argv[2]   two
 argv[3]   three

当我使用 C# 应用程序时,我唯一得到的是 argv[0] 的路径参数:

Command-line arguments:
  argv[0]   C:

任务管理器显示启动 Demo.exe 的每种方法的命令行参数: enter image description here

为什么我的 C 应用程序没有从 C# 应用程序接收命令行参数?

编辑 @hvd 建议我使用 GetCommandLine()。这是代码和结果:

char* ar = GetCommandLine();
printf( "\nGetCommandLine arguments:\n" );
printf("  %s", ar);

输出:

GetCommandLine arguments:
  "C:

C 应用程序是否有可能将参数作为一个字符串接收,但忽略了路径中第一个\之后的所有内容?

编辑:我在下面添加了一个答案。这是一种解决方法,但我不确定问题的原因。

最佳答案

我今天又回到了这个问题,并且有一个解决方法。我不明白为什么我最初的尝试没有奏效。

这是在命令行上键入 Demo.exe 和“Demo.exe”之间的区别。

C:\Users\me\Desktop\Work\Builds\Win32>Demo.exe one two three
There are 4 arguments.
Command-line arguments:
argv[0]: Demo.exe
argv[1]: one
argv[2]: two
argv[3]: three

C:\Users\me\Desktop\Work\Builds\Win32>"Demo.exe" one two three
There are 1 arguments.
Command-line arguments:
argv[0]: Demo.exe

Process.Start() 调用似乎在执行“Demo.exe”变体。

不起作用:

ProcessStartInfo startInfo = new ProcessStartInfo
{
   FileName = @"Demo.exe",
   WorkingDirectory = @"C:\Users\me\Desktop\Work\Builds\Win32",
   Arguments = "one two three"
 };
 var process = Process.Start(startInfo);

There are 1 arguments.
Command-line arguments:
argv[0]: C:

有效:

ProcessStartInfo startInfo = new ProcessStartInfo
{
   FileName = "cmd.exe",
   WorkingDirectory = @"C:\Users\me\Desktop\Work\Builds\Win32",
   Arguments = "/C Demo.exe one two three"
 };
 var process = Process.Start(startInfo);
There are 4 arguments.
Command-line arguments:
argv[0]: Demo.exe
argv[1]: one
argv[2]: two
argv[3]: three

有谁知道为什么第一种方法不起作用?

关于c# - Process.Start() 启动的应用程序未获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24000793/

相关文章:

c# - 从部署项目安装目录

c# - 测试 UI/将焦点设置在 TextBox 上

javascript - 按用户更改日期标签

VB.Net 使用 FoxIt Reader 或 Adob​​e Reader 打印 PDF

c# - 如何从 C# 执行 DOS SET 命令并使变量在 exe 关闭后保持不变?

c# - Process.Start 文件名使用 %temp%

c# - 如何使用 ProcessStartInfo 运行批处理文件?

c# - Autofixture,类作为生成的类对象?

c# - Process.Start 启动进程两次而不是一次

c# - 为进程设置环境变量