我需要从c#
代码执行shell命令,然后将shell的输出记录到文件中。
我用来执行shell命令的代码是:
using (var process = Process.Start(new ProcessStartInfo
{
FileName = fileName,
Arguments = arguments,
CreateNoWindow = false,
WindowStyle = ProcessWindowStyle.Normal,
RedirectStandardOutput = false,
UseShellExecute = true,
}))
{
// blocking wait for the process to end
process.WaitForExit();
}
我阅读了其他更改RedirectStandardOutput = true
和useShellExecute = false
的答案,以便他们可以通过获取控制台输出
string output = process.StandardOutput.ReadToEnd();
但这不会打开外壳窗口。
是否可以将命令输出显示到控制台窗口并获取该输出?
答案 0 :(得分:1)
可以使用类似的东西
using System;
using System.Diagnostics;
namespace InteractWithConsoleApp
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo cmdStartInfo = new ProcessStartInfo();
cmdStartInfo.FileName = @"C:\Windows\System32\cmd.exe";
cmdStartInfo.RedirectStandardOutput = true;
cmdStartInfo.RedirectStandardError = true;
cmdStartInfo.RedirectStandardInput = true;
cmdStartInfo.UseShellExecute = false;
cmdStartInfo.CreateNoWindow = true;
Process cmdProcess = new Process();
cmdProcess.StartInfo = cmdStartInfo;
cmdProcess.ErrorDataReceived += cmd_Error;
cmdProcess.OutputDataReceived += cmd_DataReceived;
cmdProcess.EnableRaisingEvents = true;
cmdProcess.Start();
cmdProcess.BeginOutputReadLine();
cmdProcess.BeginErrorReadLine();
cmdProcess.StandardInput.WriteLine("ping google.com.ua"); //Execute ping google.com.ua
cmdProcess.StandardInput.WriteLine("exit"); //Execute exit.
cmdProcess.WaitForExit();
}
static void cmd_DataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Output from other process");
Console.WriteLine(e.Data);
}
static void cmd_Error(object sender, DataReceivedEventArgs e)
{
Console.WriteLine("Error from other process");
Console.WriteLine(e.Data);
}
}
}