命令行c#无法正常工作

时间:2016-05-31 12:40:51

标签: c# command-line command system.diagnostics

我有以下命令要运行(当我在cmd中手动运行它时,它会起作用):

"C:\Program Files\APP\APP.exe" -CMV "C:\Program Files\APP\Second\IT" -ID 5 6 7 4 2

这是我用C#编写的代码:

string firstPath = @"""C:\Program Files\APP\APP.exe""";
string secondPath = @"""C:\Program Files\APP\Second\IT""";
string command = firstPath + " -CMV " + secondPath + " -ID 5 6 7 4 2");

我还尝试了以下代码:

int exitCode;
ProcessStartInfo processInfo;
Process process;

processInfo = new ProcessStartInfo("cmd.exe", command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;

//processInfo.Arguments 
process = Process.Start(processInfo);
process.WaitForExit();

// *** Read the streams ***
// Warning: This approach can lead to deadlocks, see Edit #2
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();

exitCode = process.ExitCode;

Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();

这似乎仍然不起作用!非常感谢任何帮助。

*********最终编辑*********

这是作为命令发送的字符串:

""C:\\Program Files\\DEEM\\DEEM.exe" -ENV "C:\\Program Files\\DEEM\\Environments\\IT" -ID 01004698001001 00285209090217 00285209090250 00285209090382 99041250643762"

导致以下错误:

  

“'C:\ Program'不被视为内部或外部   命令,\ r \ noperable程序或批处理文件。\ r \ n“

我需要做的就是取出由于命令是字符串而包装的第一个和最后一个引号。我不知道如何取出引号。

1 个答案:

答案 0 :(得分:1)

如果您等待进程退出,则第一个示例有效:

    static void Main(string[] args)
    {
        string firstPath = @"""C:\Program Files\APP\APP.exe""";
        string secondPath = @"""C:\Program Files\APP\Second\IT""";
        string command = firstPath + " -CMV " + secondPath + " -ID 5 6 7 4 2";

        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        //startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = firstPath; //"cmd.exe";
        startInfo.Arguments = command;
        process.StartInfo = startInfo;
        process.Start();

        // **** don't forget to wait for the process to exit ***
        process.WaitForExit();

        var code = process.ExitCode;
        var time = process.ExitTime;
    }

在你的第二个例子中,你 使用了WaitForExit(),但还有其他一些我没有调查过的东西。