C#如何利用cmd来执行多条命令
作者:互联网
文章目录
前言
本人最近写了个窗体程序,点击按钮后会自动调用cmd程序来运行多条oracle指令。思路是通过定义线程调用cmd程序,然后从一个txt文件里一行一行地读取记录并执行。最后再把执行的结果一行行地读取出来,展示到输出里。
一、使用步骤
1.按钮事件的编写
private void StartAudit_Click(object sender, EventArgs e)
{
StartAudit.Enabled = false; //设置按钮只可以被点击一次。
Thread newThread = new Thread(new ThreadStart(NewThread)); //定义线程
newThread.Start();//启动线程,同时启动 NewThread方法。
}
2.NewThread的方法
private void NewThread()
{
RunCmd();
}
3.运行cmd的方法
private void RunCmd()
{
using (Process p = new Process())
{
//启动cmd,并设置好相关属性。
p.StartInfo.FileName = "cmd.exe"; //确定程序名 //p.StartInfo.Arguments = "/c " + command; //确定程式命令行
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = true;//不显示程序窗口
p.Start();
//定义文件流。
FileStream fs = new FileStream("E:\\MyApp\\SqlCommand.txt",
FileMode.Open, FileAccess.Read);
StreamReader read = new StreamReader(fs, Encoding.Default);
string strReadline;
//一行行地执行命令,直到文件被读完。
while ((strReadline = read.ReadLine()) != null)
{
p.StandardInput.WriteLine(strReadline);
}
fs.Close();
read.Close();
p.StandardInput.AutoFlush = true;
//开始读文件,只要不到文件结尾,就会不停地读下去。
while (!p.StandardOutput.EndOfStream)
{
try {
string t = p.StandardOutput.ReadLine();
if (t != "")
{
SetrichTextBox(t + "\n"); //显示结果。读者随意发挥
}
if (progressBar2.Value == progressBar2.Maximum)
{
MessageBox.Show("成功!");//判断是否结束,读者随意发挥。
}
}
catch (Exception e)
{
Console.WriteLine();
}
}
}
}
二、总结
以上就是今天要讲的内容,博主在编写的过程中也踩到了很多坑,主要的问题就是一定要通过线程来调用cmd程序。以及读结果时一定要用StandardOutput.EndOfStream这一属性来判断到底是不是结束。
在编程时,找到一个合适的底层方法非常重要。如果能理解底层api的逻辑那就更强了,你的思路就会更清晰。
标签:NewThread,C#,cmd,程序,多条,new,StartInfo,true 来源: https://blog.csdn.net/weixin_43549003/article/details/110480711