C#后台执行cmd命令

发布时间:2021-05-12编辑:佚名阅读(1096)

执行且不读取流

String cmd = "dir";
Process process = new System.Diagnostics.Process()
{
    StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c" + cmd)
    { UseShellExecute = true, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden }
};
process.Start();

执行,读取数据流

String cmd = "dir";
Process process =  new Process()
{
    StartInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c" + cmd){ 
        UseShellExecute = false,
        RedirectStandardOutput = true,
        WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
    }
};
process.Start();
Console.WriteLine(process.StandardOutput.ReadToEnd());

详细流程拆解

执行且不读取流

/// <summary>
/// 执行命令,不读取信息
/// </summary>
/// <param name="command"></param>
public void ExcuteCommandOnBackgroud(String command)
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    //隐藏窗口
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    // /c : 命令执行后关闭
    // /k : 命令执行后不关闭
    command = "/c" + command;
    // 关联cmd程序
    startInfo.FileName = "cmd.exe";
    // 关联执行信息
    startInfo.Arguments = command;
    // 创建执行进程类
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    // 关联信息
    process.StartInfo = startInfo;
    // 执行
    process.Start();
}

 执行,读取数据流

/// <summary>
/// 执行命令,并获取信息
/// </summary>
/// <param name="command"></param>
public void ExcuteCommandOnBackgroudCaptureOutputStream(String command)
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    // 需要对进程执行读写流,必须设定为false
    startInfo.UseShellExecute = false;
    // 需要获取输出流
    startInfo.RedirectStandardOutput = true;
    // 隐藏窗口
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    // /c : 命令执行后关闭
    // /k : 命令执行后不关闭
    command = "/c" + command;
    // 关联cmd程序
    startInfo.FileName = "cmd.exe";
    // 关联执行信息
    startInfo.Arguments = command;
    // 创建执行进程类
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    // 关联信息
    process.StartInfo = startInfo;
    process.Start();
     
    // 逐行读取
    StreamReader reader = process.StandardOutput;
    while (!reader.EndOfStream)
    {
        Console.WriteLine(reader.ReadLine());
    }
    // 一次性读完
    // process.StandardOutput.ReadToEnd()
}


  关键字:C#后台执行cmd命令


鼓掌

0

正能量

0

0

呵呵

0


评论区