为什么通过 cmd 执行 arduino-cli 文件名在路径中带有空格不起作用?

问题描述

我正在制作一个使用 arduino-cli 编译 Arduino 代码的 C# 应用程序。我用 Process调用它,使用 ProcessStartInfo 类,当然通过 cmd.exe 调用它,这是绝对必要的。

arduino-cli.exe 忽略所有参数并在直接启动它时输出以下两行五秒钟,而不是通过 cmd.exe 或从 PowerShell 控制台中运行它:

这是一个命令行工具。

您需要打开 cmd.exe 并从那里运行它。

我可以选择正确路径的目录,但是当我选择另一个要编译的目录时,arduino-cli.exe输出错误信息:

错误:“arduino-cli”的未知命令“Studio

我认为这是因为我选择的目录位于名为 Visual Studio Projects文件夹中,名称中包含空格,我认为它将每个单词解释为单独的参数。

如何对通过 cmd.exe 传递到 arduino-cli.exe 的参数进行编码,以便在其完全限定的文件名中包含空格的两个文件名(输入和十六进制文件)作为完整的参数字符串?

我在网上读到,如果我在路径前添加 @,它应该会修复它,但它没有做太多。

当我直接在 Windows 命令提示符窗口中运行 arduino-cli 命令行而不是 C# 时,也会发生这种情况。问题可能与命令行语法有关。

这是我的 C# 代码

processstartinfo cmd = new processstartinfo();

cmd.FileName = "cmd.exe";
cmd.WindowStyle = ProcessWindowStyle.normal;

hexFile = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\cache/a";

cmd.Arguments = "/k cd " + Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\avr-g++\\arduino-cli\\bin"
  + " & arduino-cli --compile " + @inFile + " --output " + @hexFile + " multi";
            
//file = hexFile;
Process.Start(cmd);

解决方法

问题是路径太长,路径周围需要一个“”。这就是代码现在的样子 -

 ProcessStartInfo cmd = new ProcessStartInfo();

 cmd.FileName = "cmd.exe";
 cmd.WindowStyle = ProcessWindowStyle.Normal;

 string name = GenerateName(8);
 hexFile = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\cache/" + name;

 cmd.Arguments = "/k cd " + Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\avr-g++\\arduino-cli\\bin"
   + " & arduino-cli compile -b arduino:avr:uno " + "\"" + @inFile + "\"" + " --build-path " + "\"" + @hexFile + "\"";

 file = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())) + "\\cache\\" + name + "\\" + Path.GetFileName(inFile) + ".hex";
 Process.Start(cmd);
 Thread.Sleep(3000);
``