简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM