带有参数的命令行

本文关键字:命令行 参数 | 更新日期: 2023-09-27 18:22:09

我有这个代码:

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{}

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

带有参数的命令行

我解决了我的问题。它就在我身上。我试图启动命令行并给它参数,这样它就会启动另一个有参数的程序。这不是很愚蠢吗?现在我启动了我需要的带有参数的程序,它运行得很好:

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();
}

您可以尝试将/cCarries out command and then terminates)参数添加到cmd.exe:

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

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

使用如下捕获:

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

因此,发生的异常将显示出来,并将为您提供有关错误的关键信息。