我是C#的新手,所以如果我的问题没有意义,请抱歉。在我的应用程序中,C#DLL需要打开命令提示符,为Linux系统提供一个plink命令来获取系统相关的字符串并将该字符串设置为环境变量。我可以在创建C#控制台应用程序时执行此操作,使用plink命令在命令提示符下获取字符串,并使用C#中的进程类设置环境变量以打开plink作为单独的控制台进程。但是,在C#DLL中我必须打开cmd.exe 1st然后给出这个命令,我不知道如何实现?我尝试打开cmd.exe作为进程,然后尝试将输入和输出重定向到进程并给出命令并获取字符串回复,但没有运气。请让我知道任何其他解决方法。
感谢您的回答, Ashutosh说
答案 0 :(得分:5)
感谢您的快速回复。编写代码序列是我的错误。现在很少有变化,代码就像魅力一样。这是代码,
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);
到目前为止,我解释了代码...,非常感谢