使用MSDN,我得到了这个类来为我的命令行工具编写一个包装器。
我现在面临一个问题,如果我通过带有参数的命令行执行 exe,它可以完美运行而没有任何错误。
但是当我尝试从 Wrapper 传递参数时,它会使程序崩溃。
想知道我是否正确地传递了论点,如果我错了,请有人指出。这是 MSDN 的 LaunchEXE 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace SPDB
{
/// <summary>
/// Class to run any external command line tool with arguments
/// </summary>
public class LaunchEXE
{
internal static string Run(string exeName, string argsLine, int timeoutSeconds)
{
StreamReader outputStream = StreamReader.Null;
string output = "";
bool success = false;
try
{
Process newProcess = new Process();
newProcess.StartInfo.FileName = exeName;
newProcess.StartInfo.Arguments = argsLine;
newProcess.StartInfo.UseShellExecute = false;
newProcess.StartInfo.CreateNoWindow = true; //The command line is supressed to keep the process in the background
newProcess.StartInfo.RedirectStandardOutput = true;
newProcess.Start();
if (0 == timeoutSeconds)
{
outputStream = newProcess.StandardOutput;
output = outputStream.ReadToEnd();
newProcess.WaitForExit();
}
else
{
success = newProcess.WaitForExit(timeoutSeconds * 1000);
if (success)
{
outputStream = newProcess.StandardOutput;
output = outputStream.ReadToEnd();
}
else
{
output = "Timed out at " + timeoutSeconds + " seconds waiting for " + exeName + " to exit.";
}
}
}
catch (Exception e)
{
throw (new Exception("An error occurred running " + exeName + ".", e));
}
finally
{
outputStream.Close();
}
return "\t" + output;
}
}
}
这是我从主程序(Form1.cs)传递参数的方式
private void button1_Click(object sender, EventArgs e)
{
string output;
output = LaunchEXE.Run(@"C:\Program Files (x86)\MyFolder\MyConsole.exe", "/BACKUP C:\\MyBackupProfile.txt", 100);
System.Windows.Forms.MessageBox.Show(output);
}
命令行工具接受以下命令并完美运行:
C:\Program Files (x86)\MyFolder> MyConsole.exe /BACKUP C:\MyBackupProfile.txt