将控制台输出写入C#中的文件?

时间:2016-08-14 20:08:57

标签: c# streamwriter

我正在尝试将命令窗口的输出写入文件,我可以正确获取输出,并使用控制台显示它。但是,它似乎没有登录到我想要写入的文件中?

 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());
   }

1 个答案:

答案 0 :(得分:4)

当您致电ReadToEnd()时,它会读取所有内容,并且所有输出都已消耗完。你不能再打电话了。

您必须将输出存储在变量中并将其输出到控制台并写入文件。

string result = cmd.StandardOutput.ReadToEnd();
Console.WriteLine(result);
 sw.WriteLine(result);