2013-01-07 30 views
0

的標準輸出,我有一個必須閱讀應用它自己的輸出是通過如何讀取我自己的應用程序

Console.WriteLine("blah blah"); 

寫我試圖

Process p = Process.GetCurrentProcess(); 
StreamReader input = p.StandardOutput; 
input.ReadLine(); 

但它不工作因爲在第二行有「InvalidOperationException」。它說類似「StandardOutput沒有重定向,或者進程還沒有開始」(翻譯)

如何讀取我自己的輸出?還有另一種方法可以做到嗎?要完成如何編寫我自己的輸入?

輸出的應用程序已經運行。

我想讀取它的輸出住在同一個應用程序。沒有第二個應用程序。只有一個。

+0

你想要做什麼? – 2013-01-07 09:03:29

+1

爲什麼不寫一個寫入控制檯的方法,另外還要做額外的事情? – boindiil

+3

我真的很好奇......你爲什麼想這麼做? – Moriya

回答

2

我只是猜測你的意圖可能是什麼,但如果你想讀取你開始的應用程序的輸出,你可以重定向輸出。

// Start the child process. 
Process p = new Process(); 
// Redirect the output stream of the child process. 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.FileName = "Write500Lines.exe"; 
p.Start(); 
// Do not wait for the child process to exit before 
// reading to the end of its redirected stream. 
// p.WaitForExit(); 
// Read the output stream first and then wait. 
string output = p.StandardOutput.ReadToEnd(); 
p.WaitForExit(); 

例如從http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

編輯:

如果您想爲您的編輯指定您可以使用重定向當前的控制檯應用程序的輸出。

private static void Main(string[] args) 
{ 
    StringWriter writer = new StringWriter(); 
    Console.SetOut(writer); 
    Console.WriteLine("hello world"); 

    StringReader reader = new StringReader(writer.ToString()); 
    string str = reader.ReadToEnd(); 
} 
+0

你可以讓最後一個緩衝和異步,所以你可以在任何時候從不同的線程現場閱讀它? – Bitterblue

+0

如果你不能使它工作,你應該試試,並回來一個新的問題。 – Moriya

相關問題