c# 执行命令并获取输出文本

1. 一次性全获取(适合快速命令)
复制代码
void Main()
{
    var result = Execute(@"ffmpeg.exe", "-h", 10);
    result.Dump();
}

public string Execute(string filepath,string args, int seconds)
{
    string output = ""; //输出字符串 
    if (args != null && !args.Equals(""))
    {
        using (var process = new Process())//创建进程对象 
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = filepath; //设定需要执行的命令 
            startInfo.Arguments = args; //“/C”表示执行完命令后马上退出 
            startInfo.UseShellExecute = false;//不使用系统外壳程序启动 
            startInfo.RedirectStandardInput = false;//不重定向输入 
            startInfo.RedirectStandardOutput = true; //重定向输出 
            startInfo.CreateNoWindow = true;//不创建窗口 
            process.StartInfo = startInfo;
            if (process.Start())//开始进程 
            {
                if (seconds == 0)
                    process.WaitForExit();//这里无限等待进程结束 
                else
                    process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒 
                output = process.StandardOutput.ReadToEnd();//读取进程的输出 
            }
        }

    }
    return output;
}
复制代码

 2. 异步分批获取(适合长时间运行的任务,当然,要在此基础上加工一下,这只是基本原型)

复制代码
void Main()
{
    var result = string.Empty;
    Execute(@"ffmpeg.exe", "-h", out result);
    result.Dump();
}

public void Execute(string filepath, string args, out string result)
{
    using (var process = new Process())
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = filepath;
        startInfo.Arguments = args;
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.CreateNoWindow = true;
        process.StartInfo = startInfo;

        var sb = new StringBuilder();
        DataReceivedEventHandler outputHandler = (s, e) =>
        {
            if (e.Data != null)
                sb.AppendLine(e.Data);
        };

        process.ErrorDataReceived += outputHandler;
        process.OutputDataReceived += outputHandler;
        process.Start();
        process.BeginErrorReadLine();
        process.BeginOutputReadLine();
        process.WaitForExit();
        result = sb.ToString();
    }
}

// Define other methods and classes here
复制代码

 




posted on   空明流光  阅读(199)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2023-01-12 java 定时器的使用
2023-01-12 跨进程同步锁的实现方法:
2023-01-12 java 通过 nmap 跨进程内存共享

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示