【问题标题】:how to send command and receive data in command prompt in C# GUI application如何在 C# GUI 应用程序的命令提示符下发送命令和接收数据
【发布时间】:2011-04-08 19:26:45
【问题描述】:

我是 C# 新手,所以如果我的问题没有意义,请见谅。在我的 C# DLL 应用程序中,需要打开命令提示符,为 Linux 系统提供 plink 命令以获取系统相关字符串并将该字符串设置为环境变量。当我创建 C# 控制台应用程序时,我能够做到这一点,使用 plink 命令在命令提示符下获取字符串,并使用 C# 中的进程类将其设置为环境变量,以将 plink 作为单独的控制台进程打开。但是,在 C# DLL 中,我必须首先打开 cmd.exe,然后给出这个我不知道如何实现的命令?我尝试通过打开 cmd.exe 作为进程,然后尝试将输入和输出重定向到进程并给出命令并获取字符串回复,但没有运气。请告诉我任何其他解决此问题的方法。

感谢您的回答, 阿舒托什

【问题讨论】:

    标签: c#


    【解决方案1】:

    感谢您的快速回复。这是我编写代码序列的错误。现在几乎没有变化,代码就像魅力一样工作。这是代码,

        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);
    

    到目前为止,我已经解释了代码...,非常感谢

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 2011-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 2017-02-26
      相关资源
      最近更新 更多