欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#调用Windows CMD命令并返回输出结果

程序员文章站 2022-05-23 21:19:00
例子: ......

 

private static string invokeexcute(string command)
{
    command = command.trim().trimend('&') + "&exit";
    using (process p = new process())
    {
        p.startinfo.filename = "cmd.exe";
        p.startinfo.useshellexecute = false;        //是否使用操作系统shell启动
        p.startinfo.redirectstandardinput = true;   //接受来自调用程序的输入信息
        p.startinfo.redirectstandardoutput = true;  //由调用程序获取输出信息
        p.startinfo.redirectstandarderror = true;   //重定向标准错误输出
        p.startinfo.createnowindow = true;          //不显示程序窗口
        p.start();//启动程序
        //向cmd窗口写入命令
        p.standardinput.writeline(command);
        p.standardinput.autoflush = true;
        //获取cmd窗口的输出信息
        streamreader reader = p.standardoutput;//截取输出流
        string str = reader.readtoend();
        p.waitforexit();//等待程序执行完退出进程
        p.close();
        return str;
    }
}

 

例子:

string str = invokeexcute("ipconfig");
console.writeline(str);