Home > OS >  Standard output does not print date and time for each line
Standard output does not print date and time for each line

Time:10-12

I currently have a standard output process that executes a CMD command in my console application and prints the output to the log file.

The issue?

It would only print out the current date and time once before printing out the output.

Example - From log .txt file

enter image description here

What do I want to achieve?

Example

enter image description here

Current Code

static readonly string logPath = (@"C:\Temp\Test.txt");

        public static void Main()
        {

            StreamWriter logFile = new(logPath, append: true);

            var proccess = new Process
            {
                StartInfo = new ProcessStartInfo
                { 
                    FileName = "cmd.exe",
                    Arguments = "/c tsm start",
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                }
            };
            proccess.Start();

            while (!proccess.StandardOutput.EndOfStream)
            {
                string output = proccess.StandardOutput.ReadToEnd();
                if (output.Contains("successfully executed"))
                {
                    logFile.WriteLine(DateTime.Now   " "   output);
                }
        }

CodePudding user response:

Just split the output and write it line by line.

if (output.Contains("successfully executed"))
{
    var lines = output.Split(new [] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
    foreach (var line in lines)
    {
        logFile.WriteLine(DateTime.Now   " "   line);
    }
}
  • Related