C#常常操做CMD,使用的話就用下面的2和3進行整理一下使用吧。spa
一、簡單的調用命令不須要回傳數據,最簡單code
public static void ipcmd(object p) { Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/c " + p; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = false; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; process.StartInfo = startInfo; startInfo.Verb = "RunAs"; process.Start(); }
二、有回傳數據的blog
public static string CmdExcute(string cmdStr) { Process process = new Process(); string output = ""; IntPtr ptr = new IntPtr(); bool bOS_X64 = System.Environment.Is64BitOperatingSystem; if (bOS_X64) { Win32.Wow64DisableWow64FsRedirection(ref ptr); // 關閉system32文件重定向 } try { process.StartInfo.FileName = @"cmd.exe"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; if (process.Start())//開始進程 { process.StandardInput.AutoFlush = true; process.StandardInput.WriteLine(cmdStr); process.StandardInput.WriteLine("exit"); output = process.StandardOutput.ReadToEnd(); } } catch (Exception e) { } finally { if (process != null) { process.Close(); } } if (bOS_X64) { Win32.Wow64RevertWow64FsRedirection(ptr); //恢復文件重定向 } return output; } }
三、截取輸出流的進程
public static List<string> cmd(string p) { List<string> lines = new List<string>(); List<string> lineNet = new List<string>(); Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/c " + p; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = false; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; process.StartInfo = startInfo; startInfo.Verb = "RunAs"; try { process.Start(); System.IO.StreamReader reader = process.StandardOutput;//截取輸出流 while (!reader.EndOfStream) { //if (reader.ReadLine().ToString().Contains("已禁用") || reader.ReadLine().ToString().Contains("已啓用") || reader.ReadLine().ToString().Contains("Enabled") || reader.ReadLine().ToString().Contains("Disabled")) //{ lineNet.Add(reader.ReadLine()); //} } foreach (var item in lineNet) { if (item.Contains("已禁用") || item.Contains("已啓用") || item.Contains("Disabled") || item.Contains("Enabled")) { lines.Add(item); } } } catch (Exception e) { } finally { if (process != null) { process.Close(); } } return lines; }