0

我对 bat 文件中的 windows shell find 命令有问题。find 命令的输出始终为空。Bat 文件Process.Start在 C# 中使用 .NET 的方法执行。我使用输出流重定向。我想做的事:

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 包含找到的字符串出现。是否可以在批处理文件中使用 find 命令Process.Start并重定向输出流?

谢谢你的帮助。

4

2 回答 2

1

当 ShellExecute 被禁用时,您无法直接通过 Process 类启动批处理文件(并且您无法在启用 ShellExecute 的情况下重定向)。这是因为批处理文件在某种意义上并不是真正可执行的,它是资源管理器中的人为构造。

无论如何,您可以做些什么来解决它是直接使用 cmd.exe,例如将您的 ProcessStartInfo 更改为:

new ProcessStartInfo(@"cmd.exe", @"/c C:\test.bat")

并确保您等待命令退出。

于 2011-10-30T23:28:55.680 回答
0

没有更多信息,就不可能说出您遇到了什么问题。但是,以下工作:

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命令需要引用搜索字符串参数。

于 2011-10-25T22:31:27.333 回答