C#中执行Linux命令并且拿到返回值

很多应用场景,比如说获取linux系统中某个文件大小,文件内容,只要能从控制台打印的命令便可以使用此方法

 1            try
 2                   {
 3                        
 4                        var str = $"执行的命令";
 5                        Process p = new Process();
 6                        //设置要启动的应用程序
 7                        p.StartInfo.FileName = "bash";
 8                        //是否使用操作系统shell启动
 9                        p.StartInfo.UseShellExecute = false;
10                        // 接受来自调用程序的输入信息
11                        p.StartInfo.RedirectStandardInput = true;
12                        //输出信息
13                        p.StartInfo.RedirectStandardOutput = true;
14                        // 输出错误
15                        p.StartInfo.RedirectStandardError = false;
16                        //不显示程序窗口
17                        p.StartInfo.CreateNoWindow = true;
18                        p.Start();
19                        p.StandardInput.WriteLine(str);
20                        p.StandardInput.Close();
21                        var fileData = p.StandardOutput.ReadToEnd();
22                        p.WaitForExit();
23                        p.Close();
24                        _logger.LogDebug($"查看命令返回数据{fileData} {str}");
25                      
26 
27                    }
28                    catch (Exception e)
29                    {
30                        _logger.LogDebug($"{e.Message}");
31                    }

 

posted @ 2022-06-08 16:49  薛小谦  阅读(1398)  评论(0编辑  收藏  举报