2013年2月24日星期日

how to send command and receive data in command prompt in C# GUI application


Question:
I am new to C# so please sorry if i make no sense in my question. In my application which is C# DLL need to open command prompt, give a plink command for Linux system to get a system related string and set that string as environment variable. I am able to do this when i create C# console application, using plink command to get the string on command prompt and use to set it environment variable using process class in C# to open plink as separate console process. But, in C# DLL i have to open cmd.exe 1st and then give this command which i don't know how can i achieve? I tried through opening cmd.exe as process and then trying to redirect input and output to process and give command and get string reply, but no luck. Please let me know any other way to solve this.

Thanks for answers, Ashutosh

Answer:
Thanks for your quick replys. It was my mistake in writing code sequence. Now few changes and the code is working like charm. Here is code,

    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 root@susehost -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);
I explained the code so far..., thanks a lot

没有评论:

发表评论