對(duì)于C#通過程序來調(diào)用cmd命令的操作,網(wǎng)上有很多類似的文章,但很多都不行,竟是漫天的拷貝。我自己測試整理了一下。
方法一
代碼:
string str = Console.ReadLine();
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false; //是否使用操作系統(tǒng)shell啟動(dòng)
p.StartInfo.RedirectStandardInput = true;//接受來自調(diào)用程序的輸入信息
p.StartInfo.RedirectStandardOutput = true;//由調(diào)用程序獲取輸出信息
p.StartInfo.RedirectStandardError = true;//重定向標(biāo)準(zhǔn)錯(cuò)誤輸出
p.StartInfo.CreateNoWindow = true;//不顯示程序窗口
p.Start();//啟動(dòng)程序
//向cmd窗口發(fā)送輸入信息
p.StandardInput.WriteLine(str + "&exit");
p.StandardInput.AutoFlush = true;
//p.StandardInput.WriteLine("exit");
//向標(biāo)準(zhǔn)輸入寫入要執(zhí)行的命令。這里使用&是批處理命令的符號(hào),表示前面一個(gè)命令不管是否執(zhí)行成功都執(zhí)行后面(exit)命令,如果不執(zhí)行exit命令,后面調(diào)用ReadToEnd()方法會(huì)假死
//同類的符號(hào)還有&&和||前者表示必須前一個(gè)命令執(zhí)行成功才會(huì)執(zhí)行后面的命令,后者表示必須前一個(gè)命令執(zhí)行失敗才會(huì)執(zhí)行后面的命令
//獲取cmd窗口的輸出信息
string output = p.StandardOutput.ReadToEnd();
//StreamReader reader = p.StandardOutput;
//string line=reader.ReadLine();
//while (!reader.EndOfStream)
//{
// str += line + " ";
// line = reader.ReadLine();
//}
p.WaitForExit();//等待程序執(zhí)行完退出進(jìn)程
p.Close();
Console.WriteLine(output);
程序運(yùn)行結(jié)果:

需要提醒注意的一個(gè)地方就是:在前面的命令執(zhí)行完成后,要加exit命令,否則后面調(diào)用ReadtoEnd()命令會(huì)假死。
我在之前測試的時(shí)候沒有加exit命令,輸入其他命令后窗口就假死了,也沒有輸出內(nèi)容。
對(duì)于執(zhí)行cmd命令時(shí)如何以管理員身份運(yùn)行,可以看我上一篇文章:
https://cnblogs.com/babycool/p/3569183.html
方法二
另一種C#調(diào)用cmd命令的方法,不過這種方法在執(zhí)行時(shí)會(huì)“閃一下” 黑窗口,各位在使用時(shí)可以按喜好來調(diào)用。
static bool RunCmd(string cmdExe, string cmdStr)
{
bool result = false;
try
{
using (Process myPro = new Process())
{
ProcessStartInfo psi = new ProcessStartInfo(cmdExe, cmdStr);
myPro.StartInfo = psi;
myPro.Start();
myPro.WaitForExit();
result = true;
}
}
catch
{
}
return result;
}
static bool RunCmd2(string cmdExe, string cmdStr)
{
bool result = false;
try
{
using (Process myPro = new Process())
{
myPro.StartInfo.FileName = "cmd.exe";
myPro.StartInfo.UseShellExecute = false;
myPro.StartInfo.RedirectStandardInput = true;
myPro.StartInfo.RedirectStandardOutput = true;
myPro.StartInfo.RedirectStandardError = true;
myPro.StartInfo.CreateNoWindow = true;
myPro.Start();
string str = string.Format(@"""{0}"" {1} {2}", cmdExe, cmdStr, "&exit");
myPro.StandardInput.WriteLine(str);
myPro.StandardInput.AutoFlush = true;
myPro.WaitForExit();
result = true;
}
}
catch
{
}
return result;
}
作者:酷小孩
出處:cnblogs.com/babycool
該文章在 2024/4/19 17:50:44 編輯過