【问题标题】:string format in c# running command linec#运行命令行中的字符串格式
【发布时间】:2014-03-01 03:12:01
【问题描述】:

如果我在控制台中运行以下命令,它将成功:

"C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\fiji.exe" -macro "C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\macros\FFTBatch.ijm" C:\Users\myAccount.Unit\Documents\Untitled001\

在哪里 "C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\fiji.exe"是应用文件,

"C:\Users\myAccount.Unit\Favorites\Downloads\fiji.app (1)\macros\FFTBatch.ijm" 是被执行的宏文件,

C:\Users\myAccount.Unit\Documents\Untitled001\是前一个宏处理的图像。

但是,当我使用 C# 完成这项工作时,它失败了(意味着根本没有响应)。以下是相关代码:

string _fijiExeFile = "C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\fiji.exe";
string _ijmFile = "C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\macros\\FFTBatch.ijm";
string _inputDir = "C:\\Users\\myAccount.Unit\\Documents\\Untitled001\\";
string fijiCmdText = string.Format("/C \"{0}\" -macro \"{1}\" {2}", _fijiExeFile, _ijmFile, _inputDir);

try
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new        System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = fijiCmdText;
    process.StartInfo = startInfo;
    process.Start();
    _processOn = true;
    process.WaitForExit();

    ret = 1;
}
catch (Exception ex)
{
    ret = 0;
}

(路径实际上是从UI中获取的,我只是贴出它是什么。)

这是我介入时对fijiCmdText 的观察:

"/C \"C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\fiji.exe\" -macro \"C:\\Users\\myAccount.Unit\\Favorites\\Downloads\\fiji.app (1)\\macros\\FFTBatch.ijm\" C:\\Users\\myAccount.Unit\\Documents\\Untitled001\\"

如果我只使用

string fijiCmdText = string.Format("/C \"{0}\"", _fijiExeFile);

它确实会启动 .exe 应用程序,但是如果我打算添加宏文件路径,它会失败。

这里有什么问题吗?

【问题讨论】:

  • 是的。永远不要忽略异常。至少显示ex.ToString(),这样你就知道出了什么问题。
  • @JohnSaunders 它不会去异常。
  • 如果我介入却没有成功?
  • 我会得到fijiCmdText 的值,然后尝试从实际命令行运行。
  • 我粘贴了fijiCmdText的实际值,我看不出有什么问题?

标签: c# string command-line


【解决方案1】:

我发布的链接指出您需要使用 /S 开关将整个命令放在引号中:

string fijiCmdText = string.Format("/S /C \"\"{0}\" -macro \"{1}\" {2}\"", _fijiExeFile, _ijmFile, _inputDir);

或者,更清楚地说:

string fijiCmdText = "/S /C \"<command line that can have quotes>\"";

【讨论】:

  • 是的。正是 \"{0}\" 前面的 \" 解决了整个问题。想解释一下为什么?或者一个解释这个问题的链接?非常感谢!!!
  • 我认为这意味着分隔整个命令行而不是单独处理它们。
猜你喜欢
  • 2016-10-11
  • 2014-07-10
  • 2018-03-13
  • 2018-04-24
  • 2021-02-20
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多