[英]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.