c#調(diào)用dos命令
我想編一個(gè)匯編語言編輯器,但在調(diào)用masm.exe的時(shí)候,無法得到它的運(yùn)行信息。代碼如下:
process p = new process();
p.startinfo .workingdirectory ="e://";
p.startinfo.filename = "masm.exe";
p.startinfo.arguments="test.asm;";
p.startinfo.useshellexecute = false;
p.startinfo.redirectstandardoutput = true;
p.start ();
string output = p.standardoutput.readtoend();
p.waitforexit ();
//textbox1.text="aaa";
textbox1.text =output;
textbox1沒有問題,顯示別的可以,但是顯示不出來運(yùn)行時(shí)屏幕上顯示的信息,只是一片空白。
而且,當(dāng)我在系統(tǒng)下運(yùn)行cmd進(jìn)入dos時(shí),運(yùn)行masm test.asm; 有時(shí)候無任何顯示,有時(shí)候卻有編譯信息,不知道為什么。運(yùn)行其它可執(zhí)行文件也出現(xiàn)過這樣的情況。不知道和上面的問題有沒有聯(lián)系呢?
命令就確實(shí)沒有輸出。
process p = new process();
p.startinfo .workingdirectory ="c://";
p.startinfo.filename = "ping.exe";
p.startinfo.arguments="www.sina.com.cn";
p.startinfo.useshellexecute = false;
p.startinfo.redirectstandardoutput = true;
p.startinfo.createnowindow = true;
p.start ();
string output = p.standardoutput.readtoend();
p.waitforexit ();
messagebox.show(output);
c#中運(yùn)行dos命令如何隱藏dos界面
一、.net:
p = new process();
p.startinfo.filename = "cmd.exe";
// 這里是關(guān)鍵點(diǎn),不用shell啟動(dòng)/重定向輸入/重定向輸出/不顯示窗口
p.startinfo.useshellexecute = false;
p.startinfo.redirectstandardinput = true;
p.startinfo.redirectstandardoutput = true;
p.startinfo.createnowindow = true;
p.start();
p.standardinput.writeline("ping 127.0.0.1");// 向cmd.exe輸入command
p.standardinput.writeline("exit");
p.waitforexit(60000);
string s = p.standardoutput.readtoend();// 得到cmd.exe的輸出
p.close();
?
二、win32:
startupinfo si;//這里的含義太多就不一一說了,自己查msdn吧
si.cb = sizeof(si);
createprocess( "cmd.exe" , null , null , null , false , create_no_window , null , null , &si , null );
c#中的process類可方便的調(diào)用外部程序,所以我們可以通過調(diào)用cmd.exe程序
加入?yún)?shù) "/c " + 要執(zhí)行的命令來執(zhí)行一個(gè)dos命令
(/c代表執(zhí)行參數(shù)指定的命令后關(guān)閉cmd.exe /k參數(shù)則不關(guān)閉cmd.exe)
1 private string runcmd(string command)
2 {
3 //實(shí)例一個(gè)process類,啟動(dòng)一個(gè)獨(dú)立進(jìn)程
4 process p = new process();
5
6 //process類有一個(gè)startinfo屬性,這個(gè)是processstartinfo類,包括了一些屬性和方法,下面我們用到了他的幾個(gè)屬性:
7
8 p.startinfo.filename = "cmd.exe"; //設(shè)定程序名
9 p.startinfo.arguments = "/c " + command; //設(shè)定程式執(zhí)行參數(shù)
10 p.startinfo.useshellexecute = false; //關(guān)閉shell的使用
11 p.startinfo.redirectstandardinput = true; //重定向標(biāo)準(zhǔn)輸入
12 p.startinfo.redirectstandardoutput = true; //重定向標(biāo)準(zhǔn)輸出
13 p.startinfo.redirectstandarderror = true; //重定向錯(cuò)誤輸出
14 p.startinfo.createnowindow = true; //設(shè)置不顯示窗口
15
16 p.start(); //啟動(dòng)
17
18 //p.standardinput.writeline(command); //也可以用這種方式輸入要執(zhí)行的命令
19 //p.standardinput.writeline("exit"); //不過要記得加上exit要不然下一行程式執(zhí)行的時(shí)候會(huì)當(dāng)機(jī)
20
21 return p.standardoutput.readtoend(); //從輸出流取得命令執(zhí)行結(jié)果
新聞熱點(diǎn)
疑難解答
圖片精選