C# 用程序读写另一个控制台程序
2024-08-31 05:46:28
一、
using System; namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.Write(args[]);
}
}
}
编译生成ConsoleApp1.exe,并放到ConsoleApp2-bin-的Debug文件夹
using System;
using System.Diagnostics; namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "ConsoleApp1.exe";
p.StartInfo.Arguments = "a b c";//用空格来分隔参数,传给cmd.exe 时相当于传了个包含 a,b,c的字符串数组
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
//p.StartInfo.CreateNoWindow = true;//不显示程序窗口?????
p.Start();
string output = p.StandardOutput.ReadToEnd();//获取cmd窗口的输出信息
Console.WriteLine(output);
Console.ReadLine();
}
}
}
修改一下ConsoleApp2
static void Main(string[] args)
{ while ( == )
{
Console.Write("输入指令:");
string str = Console.ReadLine();
Process p = new Process();
p.StartInfo.FileName = "ConsoleApp1.exe";
p.StartInfo.Arguments = str;//用空格来分隔参数,传给cmd.exe 时相当于传了个包含 a,b,c的字符串数组
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
//p.StartInfo.CreateNoWindow = true;//不显示程序窗口?????
p.Start();
string output = p.StandardOutput.ReadToEnd();//获取cmd窗口的输出信息
p.WaitForExit();//等待程序执行完退出进程
p.Close();
Console.WriteLine("返回信息:" + output);
Console.WriteLine("");
}
}
就可以和调用的控制台交互了
但是有个问题,如果输入的字符串带空格,就会截取到空格前的字符输出
多加上双引号就可以表示成一个字符串
二、调用cmd
官方
static void Main(string[] args)
{ //Console.WriteLine("Ready to sort one or more text lines..."); using (Process myProcess = new Process())
{
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardInput = true; myProcess.Start(); StreamWriter myStreamWriter = myProcess.StandardInput; String inputText;
do
{
//Console.WriteLine("Enter a line of text (or press the Enter key to stop):"); inputText = Console.ReadLine();
if (inputText.Length > )
{
myStreamWriter.WriteLine(inputText);
}
} while (inputText.Length > ); myStreamWriter.Close(); myProcess.WaitForExit();
}
Console.ReadLine();
}
最新文章
- ASP.NET MVC3中Controller与View之间的数据传递总结
- 理解HTTP协议
- GLine游戏(Win32GUI实现,CodeBlocks+GCC编译)
- [HDU5904]LCIS(DP)
- vs2012中怎样设为起始页,怎样取消
- html的解析
- 个人简历制作(Dreamweaver)
- CreateProcess error=206, The filename or extension is too long";的一个解决方案
- web服务器、应用服务器、http服务器区别
- Div+Css的初步运用
- GridView分页的实现
- 前端性能优化:使用Data URI代替图片SRC
- HTML5之部分显示
- JS扩展方法
- Exec sql/c
- Dalvik虚拟机的优化机制
- 新秀学习SSH(十四)——Spring集装箱AOP其原理——动态代理
- Struts2学习笔记④
- (转)css内边距与外边距的区别,精辟啊
- AI - TensorFlow - 过拟合(Overfitting)