如何从c#代码执行命令 [英] How to execute a command from c#code

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

问题描述



我想通过c#代码在cmd中运行一个命令。为此我在下面使用了两个代码



Hi,
I am want to run a command in cmd through c# code. For this purpose I used below two code

System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "chkdsk";
            process.StartInfo = startInfo;
            process.Start();











and

 ProcessStartInfo procStartInfo = new ProcessStartInfo("CMD.EXE", "defrag");
 procStartInfo.WindowStyle = ProcessWindowStyle.Maximized;
 procStartInfo.RedirectStandardOutput = true;
 procStartInfo.UseShellExecute = false;
 procStartInfo.CreateNoWindow = true;
 Process pro = new Process();
 pro.StartInfo = procStartInfo;
 pro.Start();

// string result = pro.StandardOutput.ReadToEnd();
// pro.WaitForExit();





问题是,当我使用第一个代码然后它打开cmd但没有运行我想要的命令而在第二个代码的情况下它只打开cmd一秒钟并且它也没有运行那个命令。

任何人都可以帮我解决这个问题。



谢谢。



The issue is , when I used first code then it open cmd but not run the command which I want and in case of second code it open cmd for just one second and it also does't run that command.
Can anybody help me in this matter.

Thank you.

推荐答案

您必须将/ C开关传递给 CMD.exe [< a href =http://ss64.com/nt/cmd.htmltarget =_ blanktitle =New Window> ^ ]。例如

You have to pass the /C switch to CMD.exe[^]. E.g.
REM Open a new explorer window
cmd.exe /C explorer.exe





但是为什么首先通过cmd.exe传递它?



But why pass it through cmd.exe in the first place?


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

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