将控制台的输出写入 C# 中的文件?
Writing Output of Console to a file in C#?
我正在尝试将命令 window 的输出写入文件,我可以正确获取输出,并使用控制台显示它。但是,它似乎没有登录到我要写入的文件中?
using (StreamWriter sw = new StreamWriter(CopyingLocation, true))
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
string strCmdText = "Some Command";
string cmdtwo = "Some Other Command";
cmd.StandardInput.WriteLine(cmdtwo);
cmd.StandardInput.WriteLine(strCmdText);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
//Writes Output of the command window to the console properly
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
//Doesn't write the output of the command window to a file
sw.WriteLine(cmd.StandardOutput.ReadToEnd());
}
当您调用 ReadToEnd()
时,它将读取所有内容并且所有输出都已被消耗。你不能再调用它。
您必须将输出存储在变量中并将其输出到控制台并写入文件。
string result = cmd.StandardOutput.ReadToEnd();
Console.WriteLine(result);
sw.WriteLine(result);
我正在尝试将命令 window 的输出写入文件,我可以正确获取输出,并使用控制台显示它。但是,它似乎没有登录到我要写入的文件中?
using (StreamWriter sw = new StreamWriter(CopyingLocation, true))
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
string strCmdText = "Some Command";
string cmdtwo = "Some Other Command";
cmd.StandardInput.WriteLine(cmdtwo);
cmd.StandardInput.WriteLine(strCmdText);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
//Writes Output of the command window to the console properly
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
//Doesn't write the output of the command window to a file
sw.WriteLine(cmd.StandardOutput.ReadToEnd());
}
当您调用 ReadToEnd()
时,它将读取所有内容并且所有输出都已被消耗。你不能再调用它。
您必须将输出存储在变量中并将其输出到控制台并写入文件。
string result = cmd.StandardOutput.ReadToEnd();
Console.WriteLine(result);
sw.WriteLine(result);