【问题标题】:Command line with parameters带参数的命令行
【发布时间】:2012-02-25 04:21:01
【问题描述】:

我有这个代码:

string filePath = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH") + fileName;
string newFilePath = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH") + fileName.Replace(".dbf", ".csv");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH");
startInfo.FileName = "cmd.exe";
startInfo.Arguments = string.Format("\"{0}\" \"{1}\" /EXPORT:{2} /SEPTAB", ConfigurationManager.AppSettings.Get("DBF_VIEWER_PATH"), filePath, newFilePath);
try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch{}

问题是,它启动命令行,什么都不做。似乎它没有将参数传递给命令行(命令行为空)。有人知道问题出在哪里吗?

【问题讨论】:

  • 您隐藏了所有异常,因此您无法真正知道发生了什么错误...拿走那个 try/catch 并调试。
  • @JIM:那个EXE进程是你写的吗?你能改变它吗?
  • @Pedro:我试过调试,但是没有bug,没有异常。
  • @Tigran:这里没有一个 exe 文件是我的。我无法更改它们。

标签: c# command-line command-line-arguments command-prompt


【解决方案1】:

我解决了我的问题。它在我身上。我试图启动命令行并为其提供参数,因此它将启动另一个带有参数的程序。那不是很愚蠢吗? 现在我用参数启动我需要的程序,它运行良好:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WorkingDirectory = ConfigurationManager.AppSettings.Get("FILE_SAVE_PATH");
startInfo.FileName = ConfigurationManager.AppSettings.Get("DBF_VIEWER_PATH");
startInfo.Arguments = string.Format("\"{0}\" /EXPORT:{1} /SEPTAB", filePath, newFilePath);
using (Process exeProcess = Process.Start(startInfo))
{
    exeProcess.WaitForExit();
}

【讨论】:

  • 我会,但系统不允许我这样做。我得等到明天:)
【解决方案2】:

您可以尝试在 cmd.exe 中添加 /c (Carries out command and then terminates) 参数:

startInfo.Arguments = string.Format("/c \"{0}\" \"{1}\" /EXPORT:{2} /SEPTAB", ConfigurationManager.AppSettings.Get("DBF_VIEWER_PATH"), filePath, newFilePath);

编辑:正如 Pedro 所说,您确实应该避免使用 catch{},因为它会隐藏任何抛出的异常。

【讨论】:

  • 我删除了try{} catch{},也不例外。使用/c 它启动命令行并关闭它,但不执行任何命令。如果我使用文本可视化工具并将参数粘贴到命令行,则表示无法识别 /c
【解决方案3】:

像这样使用 catch:

try
{
    using (Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
}
catch(Exception ex)
{
     Console.Writeline(ex.ToString());
     Console.ReadKey();
}

因此将显示发生的异常,并为您提供有关问题所在的重要信息。

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2014-02-11
    • 2013-11-24
    • 2019-08-15
    • 2011-10-31
    • 2020-11-08
    相关资源
    最近更新 更多