【发布时间】:2015-06-18 11:44:14
【问题描述】:
我正在尝试将批处理文件执行的输出重定向到控制台应用程序的主窗口。
我正在调用该方法来运行这样的过程:
this.runProcess("\\bar\foo\blah\", "myBatch1.bat", "bat");
被调用的方法如下:
public void runProcess(string aPath,string aName,string aFiletype)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Started: {0}",DateTime.Now.ToString("dd-MMM hh:mm:ss"));
Console.WriteLine("Will try run this file {0} {1}",aPath,aName);
Console.WriteLine("File type {0}",aFiletype);
string stInfoFileName;
string stInfoArgs;
if(aFiletype == "bat")
{
stInfoFileName = @"cmd.exe";
stInfoArgs = "//c " + aName;
}
else
{ //vbs
stInfoFileName = @"cscript";
stInfoArgs = "//B " + aName;
}
this.aProcess.StartInfo.FileName = stInfoFileName;
this.aProcess.StartInfo.Arguments = stInfoArgs;
this.aProcess.StartInfo.WorkingDirectory = @aPath;
this.aProcess.StartInfo.CreateNoWindow = true;
this.aProcess.StartInfo.UseShellExecute = false;
this.aProcess.StartInfo.RedirectStandardError = true;
this.aProcess.StartInfo.RedirectStandardOutput = true;
this.aProcess.Start();
Console.WriteLine("<<<got to here");
Console.WriteLine(this.aProcess.StandardOutput.ReadToEnd());
Console.WriteLine(this.aProcess.StandardError.ReadToEnd());
this.aProcess.WaitForExit(); //<-- Optional if you want program running until your script exit
this.aProcess.Close();
Console.WriteLine("Finished: {0}",DateTime.Now.ToString("dd-MMM hh:mm:ss"));
}
为了弄清楚发生了什么,我添加了对 WriteLine 的额外调用。"<<<got to here" 被写入控制台,然后它就挂起,没有进一步的事情发生。
怀疑我的错误是非常微不足道的,因为我对这项技术的经验有限。
我做错了什么?
【问题讨论】:
-
为什么字符串中有双斜杠?这可能是
cmd /c不起作用的原因,因为您实际上发送的是命令处理器不接受的cmd //c。 -
另外,如果你想让子进程的输出到控制台,你为什么要打开重定向?如果重定向关闭,则输出应转到控制台而不需要任何额外的代码。
-
@HarryJohnston 好的 - 不确定双斜线出现在哪里,我将修改为
"/c "和"/B "。就输出而言,我认为它默认被定向到批处理文件的子应用程序窗口,所以要将其定向到不同的位置重定向需要打开吗? (......但我第一次使用这些方法时感觉在黑暗中)。还有 Harry - 我目前正在使用的代码中此线程中的最后一篇文章...... -
如果父进程有控制台,则子进程默认使用相同的控制台——换句话说,不应该有子窗口,前提是
UseShellExecute设置为false。 (您也不需要设置CreateNoWindow。) -
- 批处理文件通过单独的客户端应用程序将文件发送到 ftp。我试图通过注释掉你提到的行来简化它,它抛出了一个错误。我已将以下代码更新为我的工作版本。标记为
//<<HJ的两行一旦被注释掉就会导致错误。如果您想为我简化并测试一个工作版本,我会非常有兴趣使用它..
标签: c# batch-file process console-application