【问题标题】:Standard output does not print date and time for each line标准输出不打印每一行的日期和时间
【发布时间】:2021-11-30 15:35:12
【问题描述】:

我目前有一个标准输出进程,它在我的控制台应用程序中执行 CMD 命令并将输出打印到日志文件。

问题?

它只会在打印输出之前打印一次当前日期和时间。

示例 - 来自日志 .txt 文件

我想实现什么?

例子

当前代码

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

【问题讨论】:

  • output.Contains("successfully executed") 表示如果任何输出 /contains/ 来自 CMD 输出 '/c tsm start' 的字符串“成功执行”(不等于),它将打印日期和时间 + 整个输出。您看到的代码是实际代码并且运行良好,我正在尝试将 DateTime 添加到每一行。
  • 以下可能会有所帮助:stackoverflow.com/questions/68429665/…
  • 请按原样发布文字(正确的formatted!)而不是图片!

标签: c# .net visual-studio logging cmd


【解决方案1】:

只需拆分输出并逐行写入。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2018-11-25
    • 2013-05-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多