gpt4 book ai didi

c# - 如何在 C# GUI 应用程序的命令提示符下发送命令和接收数据

转载 作者:行者123 更新时间:2023-11-30 15:08:25 24 4
gpt4 key购买 nike

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

感谢您的回答,阿舒托什

最佳答案

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

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

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

关于c# - 如何在 C# GUI 应用程序的命令提示符下发送命令和接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5591089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com