【问题标题】:C# index out of range when i run exe from command line and pass arguments to it [closed]当我从命令行运行 exe 并将参数传递给它时,C# 索引超出范围[关闭]
【发布时间】:2021-09-02 12:28:55
【问题描述】:

这是我编译并获取其 exe 的代码:

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

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

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

这是我在 powershell 中写的:

>.\run.bat 

这是错误:

一些/路径/...>“app.exe”“路径/到/项目”“项目”
未处理的异常。 System.IndexOutOfRangeException:索引超出了数组的范围。
在 path/to/app.cs:line 12 中的 theApp.Main(String[] args) 处

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

【问题讨论】:

  • 打开标准命令提示符(cmd.exe,而不是 powershell)。粘贴到`“app.exe”“some text1”“some text2”`并运行它。会发生什么?
  • 您直接访问args,而没有先检查是否有任何args。在你提供它们的 bat 中,因此一切正常,但你的 powershell 版本没有参数,并且由于缺少这些参数而出现错误。
  • @Alejandro but your powershell version has no arguments 你是怎么得出这个结论的?
  • @mjwills 因为问题是这样说的:this is what i write in powershell:>.\run.bat
  • @mjwills 同样的错误

标签: c# command-line exe


【解决方案1】:

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

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

如您所见,没有错误:

【讨论】:

  • 我的 powershell 版本是 5.1.19041.1151。但是当我在 cmd 中运行 '"app.exe" "some text1" "some text2"' 时,我得到了同样的错误。
  • 在 cmd: F:\Programing\C#\ConsoleAppAndDictionary\Dict\Generator>"DictionaryGenerator.exe" "F:\Programing\C#\ConsoleAppAndDictionary\Dict\" "Dict" 未处理的异常。 System.IndexOutOfRangeException:索引超出了数组的范围。在 F:\Programing\C#\DictionaryGenerator\DictionaryGenerator\DictionaryGeneratorRunner.cs:line 12 中的 DictGenerator.DictionaryGeneratorRunner.Main(String[] args)
  • 也可以从 cmd 为我工作。
【解决方案2】:

问题出在我写这个的 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 中或当我尝试运行保存的命令时,它认为 \" 是转义序列。

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多