[英]FIND shell command does not work when executing with .NET Process.Start with redirected output streams
我在bat文件中的Windows shell find命令有问题。 find命令的输出始终为空。 Bat文件是使用C#中的.NET的Process.Start
方法执行的。 我使用输出流重定向。 我想做的事:
ProcessStartInfo processInfo = new ProcessStartInfo("c:\test.bat")
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process testProcess = new Process();
testProcess.EnableRaisingEvents = true;
testProcess.OutputDataReceived += new DataReceivedEventHandler(testProcess_OutputDataReceived);
testProcess.ErrorDataReceived += new DataReceivedEventHandler(testProcess_ErrorDataReceived);
testProcess.StartInfo = processInfo;
testProcess.Start();
批处理文件(c:\\ test.bat)包含带有重定向到输出文件的find命令:
find /I "TestString" "c:\TestInput.xml" > output.txt
重定向outputStream可以正常工作,但是output.txt的内容为空(文件大小为0B)。 当我执行相同的批处理命令时,output.txt包含发现的字符串出现。 是否可以在处理Process.Start
和重定向输出流的批处理文件中获取find命令?
谢谢你的帮助。
禁用ShellExecute时,不能直接通过Process类直接启动批处理文件(并且不能在启用ShellExecute的情况下进行重定向)。 这是因为批处理文件在某种意义上并不是真正可执行的,它是资源管理器中的人为构造。
无论如何,您可以直接使用cmd.exe来解决此问题,例如将ProcessStartInfo更改为:
new ProcessStartInfo(@"cmd.exe", @"/c C:\test.bat")
还要确保您等待命令退出。
没有更多信息,就无法说出您遇到了什么问题。 但是,以下工作原理:
var find = new Process();
var psi = find.StartInfo;
psi.FileName = "find.exe";
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
// remember to quote the search string argument
psi.Arguments = "\"quick\" xyzzy.txt";
find.Start();
string rslt = find.StandardOutput.ReadToEnd();
find.WaitForExit();
Console.WriteLine("Result = {0}", rslt);
Console.WriteLine();
Console.Write("Press Enter:");
Console.ReadLine();
return 0;
在示例文件中运行该命令所得到的结果与使用相同参数从命令行运行find
时得到的结果相同。
可能会使您失望的是, find
命令要求将搜索字符串参数加引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.