当我从命令行执行 运行 并将参数传递给它时,C# 索引超出范围

C# index out of range when i run exe from command line and pass arguments to it

这是我编译得到exe的代码:

private static void Main(string[] args)
{
    var t1 = args[0];
    var t2 = args[1];
}

这是我在 .bat 文件中写的:

"app.exe" "text\" "text"

这是我在 powershell 中写的:

>.\run.bat 

这是错误:

some/path/...>"app.exe" "path/to/project" "project"
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
at theApp.Main(String[] args) in path/to/app.cs:line 12

这很奇怪,因为当我直接在 powershell 中编写并按 enter 时,我在 bat 文件中编写的行工作得很好,但是当我尝试从另一个 powershell 控制台 运行 bat 文件时,它的行为有所不同。

首先注意args中的第一个参数是程序名,实际参数从args[1]开始。 其次,您 运行 是哪个 PowerShell 版本?我尝试使用 PowerShell 7 重现您的问题,但未能成功,这是我的尝试:

  1. 我在 VS 代码 .exe 文件夹中创建了 run.bat 内容 "code.exe" "." 以便在当前文件夹中启动 VS 代码。
  2. 我在此文件夹中启动了 PowerShell 7 会话
  3. 我像你一样执行了 .\run.bat 并且 VS Code 按预期打开了

如您所见,没有错误:

问题出在我写的 bat 文件中:

"app.exe" "a text that ends like this\" "some other text"

在第一个参数的末尾有一个 \" 所以我将其更改为 \\" 现在一切正常。 似乎当我直接在命令行中写“sometext\”时,它读起来像 sometext\,但是当我将这个命令保存在 bat 文件中并尝试从其他地方 运行 这个它读起来像 sometext”是我的输入文本所以它把第二个参数(“othertext”)附加到第一个参数(“sometext\”)然后我的 C# 代码只得到一个这样的参数:sometext" othertext.

P.S:当我在 powershell 中编写命令时,它认为 \" 不是转义序列,但在 cmd 中或者当我尝试 运行 保存命令时,它认为 \" 是一个转义序列。