2011-04-08 27 views
3

我是C#的新手,所以如果我對我的問題沒有任何意義,請對不起。在我的應用程序中,C#DLL需要打開命令提示符,爲Linux系統提供一個plink命令來獲取與系統相關的字符串並將該字符串設置爲環境變量。當我創建C#控制檯應用程序時,我可以這樣做,使用plink命令獲取命令提示符處的字符串,並使用C#中的進程類將其設置爲環境變量,以便將plink作爲單獨的控制檯進程打開。但是,在C#DLL中,我必須打開cmd.exe 1st,然後給出這個命令,我不知道我該如何實現?我嘗試通過打開cmd.exe作爲進程,然後嘗試重定向輸入和輸出進程並給出命令並獲得字符串回覆,但沒有運氣。請讓我知道任何其他方式來解決這個問題。如何在C#GUI應用程序中的命令提示符下發送命令和接收數據

感謝答案, Ashutosh說

回答

4

感謝您的快速回信。編寫代碼序列是我的錯誤。現在幾乎沒有什麼變化,代碼就像魅力一樣工作。下面是代碼,

string strOutput; 
    //Starting Information for process like its path, use system shell i.e. control process by system etc. 
    ProcessStartInfo psi = new ProcessStartInfo(@"C:\WINDOWS\system32\cmd.exe"); 
    // its states that system shell will not be used to control the process instead program will handle the process 
    psi.UseShellExecute = false; 
    psi.ErrorDialog = false; 
    // Do not show command prompt window separately 
    psi.CreateNoWindow = true; 
    psi.WindowStyle = ProcessWindowStyle.Hidden; 
    //redirect all standard inout to program 
    psi.RedirectStandardError = true; 
    psi.RedirectStandardInput = true; 
    psi.RedirectStandardOutput = true; 
    //create the process with above infor and start it 
    Process plinkProcess = new Process(); 
    plinkProcess.StartInfo = psi; 
    plinkProcess.Start(); 
    //link the streams to standard inout of process 
    StreamWriter inputWriter = plinkProcess.StandardInput; 
    StreamReader outputReader = plinkProcess.StandardOutput; 
    StreamReader errorReader = plinkProcess.StandardError; 
    //send command to cmd prompt and wait for command to execute with thread sleep 
    inputWriter.WriteLine("C:\\PLINK -ssh [email protected] -pw opensuselinux echo $SHELL\r\n"); 
    Thread.Sleep(2000); 
    // flush the input stream before sending exit command to end process for any unwanted characters 
    inputWriter.Flush(); 
    inputWriter.WriteLine("exit\r\n"); 
    // read till end the stream into string 
    strOutput = outputReader.ReadToEnd(); 
    //remove the part of string which is not needed 
    int val = strOutput.IndexOf("-type\r\n"); 
    strOutput = strOutput.Substring(val + 7); 
    val = strOutput.IndexOf("\r\n"); 
    strOutput = strOutput.Substring(0, val); 
    MessageBox.Show(strOutput); 

我那麼遠,解釋的代碼,非常感謝

相關問題