C#通过进程调用批处理文件并且能够通过错误重定向和cmd运行exe文件

3
我使用以下代码创建进程:
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.WorkingDirectory = buildProject.DirectoryName;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;

然后我启动这个过程并传递一些指令给它:
process.Start();

StreamWriter stream = process.StandardInput;

// call batch
stream.WriteLine(@"call ""test.bat""");

// call exe
stream.WriteLine("echo msbuild!");

// exit-command
stream.WriteLine("exit");

所有的工作正常,直到批处理文件包含两个NUL重定向:

@call :Jump_1
@call :Jump_2

@goto end


@REM -----------------------------------------------------------------------
:Jump_1
@echo Jump_1
@call :Jump_1_1 1>nul 2>&1                   REM critical!!!
@exit /B 0

:Jump_1_1
@echo Jump_1_1
@exit /B 0


@REM -----------------------------------------------------------------------
:Jump_2
@echo Jump_2
@call :Jump_2_1 1>nul 2>&1                   REM critical!!!
@exit /B 0

:Jump_2_1
@echo Jump_2_1
@exit /B 0


@REM -----------------------------------------------------------------------
@echo End
:end

在这种情况下,进程会立即停止。StandardOut 显示如下内容:

Microsoft Windows XP [版本 5.1.2600]

(C) 版权所有 1985-2001 Microsoft Corp.

C:\Entwicklung\ProcessTest\ProcessTest\bin\Debug>call "test.bat"

Jump_1

Jump_2

如果只有一个重定向,那么一切都正常,只有两个重定向时才会崩溃。
由于原始脚本是使用 VS2010 提供的,因此无法更改该脚本。
编辑:我已更新问题并提供了更多细节。

将.bat文件作为进程启动,而不是cmd.exe不起作用吗? - Ash Burlaczenko
即使我禁用了StandardInput,仍然会遇到相同的问题。 - lippo
3
重定向到 NUL 失败了,还是将标准错误重定向到标准输出(2>&1)失败了?你的代码没有将 RedirectStandardError 设置为 true... - Bob Vale
这是从stderror到stdout的重定向。RedirectStandardError=true解决了这个问题。谢谢! - lippo
@BobVale,您能否在下面以答案的形式发布您的评论,这样我们就可以将其从未回答的列表中移除了吗?谢谢。 - Bill the Lizard
1个回答

1

是重定向到 nul 失败了,还是从 stderror 重定向到 stdout (2>&1) 失败了?

你的代码没有将 RedirectStandardError 设置为 true,你应该将其设置为 true,这样它就可以工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接