从C#执行cmd命令时出现问题 [英] Problem while executing cmd command from C#

查看:453
本文介绍了从C#执行cmd命令时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在C#中创建类似bash的shell,

好​​吧,为了执行cmd命令,我启动cmd.exe,隐藏它,并在我的控制台应用程序中显示输出使用此代码:

So I am trying to make a bash-like shell in C#,
Well, for executing cmd commands I am starting the cmd.exe, hidding it, and displaying the output in my Console Application using this code :

Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("Microsoft(R) Windows(R) Command Prompt");
Console.ForegroundColor = ConsoleColor.White;
Console.Write("@bash!~cmd: ");
string cmdimput = Console.ReadLine();
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = cmdimput;
cmd.StartInfo.RedirectStandardError = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.ErrorDialog = false;
cmd.Start();
StreamWriter inputWriter = cmd.StandardInput;
StreamReader outputReader = cmd.StandardOutput;
StreamReader errorReader = cmd.StandardError;
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
Console.ReadLine();



问题是我的应用程序在输入参数后按下回车后立即停止,

无输出/输入和找到错误信息,它只是挂起....



帮助将不胜感激...

@bash!cmd~:Sids123 :P


The problem is that my Application halts as soon as I press enter after entering an argument,
No Output/Input and error messages are found, It just hangs....

Help Would be appreciated...
@bash!cmd~: Sids123 :P

推荐答案

由于您直接启动cmd.exe,它将启动并等待用户关闭窗口。但是既然你已经隐藏了它,那么用户就不会知道他必须关闭它,或者如果他猜到他应该关闭它,如何关闭它。



然后说WaitForExit - 所以你的应用程序阻止等待用户关闭他看不到的窗口,无法触摸,也不知道是否有...



这会让你感到惊讶吗?



尝试从窗口中删除隐藏的样式,你会明白我的意思。哦,如果你已经多次测试过,你可能想用任务管理器来关闭那些隐藏的窗口...



我不太确定你想用这个来实现什么,但这不是你的方法。
Since you start cmd.exe directly, it will start and wait for the user to close the window. But since you have hidden it, the user won't know that he has to close it, or how to close it if he guesses that he should.

You then say WaitForExit - so your application blocks waiting for the user to close a window he can't see, can't touch, and doesn't know is there...

And this surprises you?

Try removing the Hidden style from your window, and you'll see what I mean. Oh, and if you have tested this several times, you might want to use the Task Manager to shut down those hidden windows...

I'm not exactly sure what you are trying to achieve with this, but that isn't the way to do it.


这篇关于从C#执行cmd命令时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆