簡體   English   中英

如何讀取我自己的應用程序的標准輸出

[英]How to read standard output of my own application

我有一個應用程序,必須讀取它自己的輸出,該輸出是通過以下方式編寫的

Console.WriteLine("blah blah");

我正在努力

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

但是由於第二行的“ InvalidOperationException”而無法使用。 上面寫着“未重定向StandardOutput或進程尚未開始”之類的內容(翻譯)

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

具有輸出的應用程序已在運行。

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

我只是在猜測您的意圖是什么,但是如果您想從啟動的應用程序中讀取輸出,則可以重定向輸出。

 // 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/zh-cn/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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM