如何在C#中执行命令 [英] How to Execute a Command in C#

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

问题描述



我正在尝试创建一个与命令提示符shell(cmd.exe)交互的Windows Forms C#项目。

我想打开命令提示符,发送命令(如ipconfig)然后将结果读回windows窗体,并可以下载结果的相关文件。

我卡住了。 help .....

Hi,
I am trying to create a Windows Forms C# project that interacts with the command prompt shell (cmd.exe).
I want to open a command prompt, send a command (like ipconfig) and then read the results back into the windows form ,and can download the related file of the results.
I am stuck. help.....

推荐答案

问题出在这里:ipconfig不是命令,这是一个常规应用程序。因此,CMD.EXE是完全冗余的,不应该使用。



对于注册用于某些应用程序的文件类型的数据文件也是如此,因此shell API了解它们。在所有这些情况下,您只需使用 System.Diagnostics.Process.Start 以及文件名和命令行参数。例如:

Here is the problem: ipconfig is not a "command", this is a regular application. So, "CMD.EXE" is totally redundant and should not be used.

The same goes for data files with file types registered for use with certain application, so the shell API knows about them. In all such cases, you just use System.Diagnostics.Process.Start with the file name and command line parameters. For example:
System.Diagnostics.Process.Start("ipconfig.ехе", "/allcompartments");



剩下的问题是使用重定向流 StandardOutput ,以防万一, StandardError 。在这些MSDN页面上演示了重定向的使用:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx [ ^ ] 。



参见:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx [ ^ ]。



-SA


The remaining problem is using redirected streams StandardOutput and, just in case, StandardError. The use of redirection is demonstrated on these MSDN pages:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx[^],
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror.aspx[^].

See also:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx[^],
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx[^].

—SA


请看这个链接:



C# - 使用命令提示符 [ ^ ]
Please see this link:

C# - Using the Command Prompt[^]


这篇关于如何在C#中执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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