当前位置: 移动技术网 > IT编程>开发语言>.net > C#调用Windows CMD命令并返回输出结果

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

2018年11月20日  | 移动技术网IT编程  | 我要评论

九花娘误食龙卵,qq空间男生头像,斋藤支静加

 

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);

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网