[英]Writing Output of Console to a file in C#?
我試圖將命令窗口的輸出寫入文件,我可以正確獲取輸出,並使用控制台顯示它。 但是,它似乎沒有登錄到我要寫入的文件中?
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.