我在bat文件中使用windows shell查找命令有问题。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 /I "TestString" "c:TestInput.xml" > output.txt
outputStream的重定向工作正常,但output.txt的内容为空(文件大小为0B)。当我执行相同的批处理命令时,output.txt包含找到的字符串。是否有可能在批处理文件中使用Process.Start
和重定向的输出流获得查找命令?
谢谢你的帮助。
当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
命令要求将搜索字符串参数加引号。