C#中隐式运行CMD命令行窗口的方法
2024-08-25 07:13:54
using System;
using System.Diagnostics;
namespace Business
{
/// <summary>
/// Command 的摘要说明。
/// </summary>
public class Command
{
private Process proc = null;
/// <summary>
/// 构造方法
/// </summary>
public Command()
{
proc = new Process();
}
/// <summary>
/// 执行CMD语句
/// </summary>
/// <param name="cmd">要执行的CMD命令</param>
public void RunCmd(string cmd)
{
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.StandardInput.WriteLine(cmd);
proc.Close();
}
/// <summary>
/// 打开软件并执行命令
/// </summary>
/// <param name="programName">软件路径加名称(.exe文件)</param>
/// <param name="cmd">要执行的命令</param>
public void RunProgram(string programName,string cmd)
{ System.Diagnosties.Process p=new System.Diagnosties.Process();
p.StartInfo.FileName="cmd.exe";//要执行的程序名称
p.StartInfo.UseShellExecute=false;
p.StartInfo.RedirectStanderInput=true;//可能接受来自调用程序的输入信息
p.StartInfo.RedirectStanderOutput=true;//由调用程序获取输出信息
p.StartInfo.CreateNoWindow=true;//不显示程序窗口
p.Start();//启动程序
//向CMD窗口发送输入信息:
p.StanderInput.WriteLine("shutdown -r t 10"); //10秒后重启(C#中可不好做哦)
//获取CMD窗口的输出信息:
string sOutput = p.StandardOutput.ReadToEnd();有啦以下代码,就可以神不知鬼不觉的操作CMD啦。总之,Process类是一个非常有用的类,它十分方便的利用第三方的程序扩展了C#的功能。 if (cmd.Length != )
{
proc.StandardInput.WriteLine(cmd);
}
proc.Close();
}
/// <summary>
/// 打开软件
/// </summary>
/// <param name="programName">软件路径加名称(.exe文件)</param>
public void RunProgram(string programName)
{
this.RunProgram(programName,"");
}
}
}
调用时
Command cmd = new Command();
cmd.RunCmd("dir");
获取输出信息应注意:
ReadtoEnd()容易卡住:
string outStr = proc.StandardOutput.ReadtoEnd();
更倾向于使用ReadLine():
[csharp] view plaincopyprint?string tmptStr = proc.StandardOutput.ReadLine();
string outStr = "";
while (tmptStr != "")
{
outStr += outStr;
tmptStr = proc.StandardOutput.ReadLine();
}
调用第三方exe时可以使用如下:
/// <summary>
/// 执行ThermSpy.exe
/// </summary>
private void CmdThermSpy()
{
Process p = new Process();
p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
p.StartInfo.FileName = "ThermSpyPremium.exe";
p.StartInfo.Arguments = "-header:gpu -datetime -log:NV_clock.log";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
}
最新文章
- Angular2入门系列教程4-服务
- oracle中查询、禁用、启用、删除表外键
- 个人作业——关于K米的产品案例分析
- Logstash-5.0同步.json文件到ElasticSearch-5.0配置文件
- 移动web开发介绍——浏览器
- 视频转gif
- Android获取屏幕长宽
- sql server 2012 自定义聚合函数(MAX_O3_8HOUR_ND) 计算最大的臭氧8小时滑动平均值
- typedef用法小结
- Xamarin App文件(apk)大小和启动时间的影响因素
- HDFS配额管理(实战)
- CentOS 7 配置网络连接
- 网络小白之WAN与LAN的区别
- Shell命令-文件及内容处理之wc,tr
- Beta冲刺(2/7)
- Codeforces 1012D AB-Strings 贪心
- java.lang.UnsupportedClassVersionError: xxx/xxxClass : Unsupported major.minor version 51.0【转】
- Thinking in Java---异常处理机制
- 预则立&;&;他山之石--团队计划、访谈优秀前辈
- smtpclient 邮件发送测试