2012-12-21 36 views
1

方法,如果我哪裏有可執行文件(可執行文件是不是一個C#應用程序包含非託管代碼,但是代碼是相似的)對第三方的EXE執行從我自己的控制檯應用程序

// ConsoleApplication1.exe 

class Program  
{ 
    static void Main() 
    { 
     while (true) 
     { 
      System.Console.WriteLine("Enter command"); 

      var input = System.Console.ReadLine(); 

      if (input == "a") 
       SomeMethodA(); 
      else if (input == "b") 
       SomeMethodB(); 
      else if (input == "exit") 
       break; 
      else 
       System.Console.WriteLine("invalid command"); 
     } 
    } 

    private static void SomeMethodA() 
    { 
     System.Console.WriteLine("Executing method A"); 
    } 

    private static void SomeMethodB() 
    { 
     System.Console.WriteLine("Executing method B"); 
    } 
} 

話,怎麼可能我從c#執行SomeMethodA()

這是我制定了到目前爲止

 Process p = new Process(); 

     var procStartInfo = new ProcessStartInfo(@"ConsoleApplication1.exe") 
     { 
      UseShellExecute = false, 
      RedirectStandardOutput = true, 
     }; 

     p.StartInfo = procStartInfo; 

     p.Start(); 

     StreamReader standardOutput = p.StandardOutput; 

     var line = string.Empty; 

     while ((line = standardOutput.ReadLine()) != null) 
     { 
      Console.WriteLine(line); 

      // here If I send a then ENTER I will execute method A! 
     } 

回答

1

如果你只是想通過「一」,所以SomeMethodA執行,你可以做到這一點

Process p = new Process(); 

    var procStartInfo = new ProcessStartInfo(@"ConsoleApplication1.exe") 
    { 
     UseShellExecute = false, 
     RedirectStandardOutput = true, 
     RedirectStandardInput = true, //New Line 
    }; 

    p.StartInfo = procStartInfo; 

    p.Start(); 

    StreamReader standardOutput = p.StandardOutput; 
    StreamWriter standardInput = p.StandardInput; //New Line 

    var line = string.Empty; 


    //We must write "a" to the other program before we wait for a answer or we will be waiting forever. 
    standardInput.WriteLine("a"); //New Line 

    while ((line = standardOutput.ReadLine()) != null) 
    { 
     Console.WriteLine(line); 

     //You can replace "a" with `Console.ReadLine()` if you want to pass on the console input instead of sending "a" every time. 
     standardInput.WriteLine("a"); //New Line 
    } 

如果你想一起繞過輸入過程,這是一個非常困難的問題(如果方法不是私人的,它會更容易),我會刪除我的答案。


P.S.你應該包裝你的兩個流媒體閱讀器using陳述

using (StreamReader standardOutput = p.StandardOutput) 
using (StreamWriter standardInput = p.StandardInput) 
{ 
    var line = string.Empty; 

    standardInput.WriteLine("a"); 

    while ((line = standardOutput.ReadLine()) != null) 
    { 
     Console.WriteLine(line); 

     standardInput.WriteLine("a"); 
    } 
} 
+0

非常感謝! –

相關問題