当我通过代码执行脚本时,它会陷入无限循环。但是相同的脚本可以在CMD中工作
尝试使用CMD并且可以正常工作,但不能在代码中工作。以任何VB脚本为例并进行验证。
private string excecuteScript(string retValue)
{
try
{
string filetoexecute = Path.Combine(Application.StartupPath, Path.GetExtension(ScriptName).EndsWith(".vbs",StringComparison.InvariantCultureIgnoreCase) ? "AA_MyVB.vbs" : "AA_MyJS.js");
filetoexecute = string.Format("\"" + filetoexecute + "\"");
string arguments = " " + filetoexecute + " " + ScriptInputPara + " \"" + ScriptName + "\" ";
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = Path.Combine(Environment.SystemDirectory, "WScript.exe"),
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var myProcess = CommonMethods.InvokeProcess(startInfo);
StreamReader errorStream = myProcess.StandardError;
StreamReader outputStream = myProcess.StandardOutput;
string theOutput = string.Empty;
bool stopWhile = false;
while (!stopWhile)
{
stopWhile = myProcess.HasExited;
if (CmdTask.IsTaskTimedout)
{
stopWhile = true;
myProcess.Kill();
}
}
theOutput += outputStream.ReadLine();
TheError += errorStream.ReadToEnd();
if (myProcess.ExitCode != 0)
{
TheError = "Error occurred while executing script file";
}
if (IsScriptTask && !string.IsNullOrEmpty(theOutput) && !string.IsNullOrEmpty(ScriptOutputPara))
CmdTask.SetVariableValue(ScriptOutputPara, theOutput);
}
catch (Exception ex)
{
retValue = (ex.Message);
}
return retValue;
}
实际:myProcess.HasExited
返回false
预期:myProcess.HasExited
返回true
如果我在while循环之前执行theOutput += outputStream.ReadLine();
,则myProcess.HasExited
返回true ...