使用MSDN,我得到了一个为我的命令行工具编写包装器的类。
现在我面临一个问题,如果我通过带参数的命令行执行exe文件,它可以完美地工作而没有任何错误。
但是当我尝试从包装器中传递参数时,程序会崩溃。
想知道我是否正确地传递了参数,如果我错了,有人能指出来吗?这是来自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