Search code examples
c#streamwriter

Writing Output of Console to a file in C#?


I'm trying to write the output of the command window to a file, I can get the output correctly, and display it using console. However, it doesn't seem to get logged into the file that I want to write to?

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

Solution

  • When you call ReadToEnd() it will read everything and all the output has been consumed. You can't call it again.

    You have to store the output in a variable and output that to the console and write to a file.

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